babylon.max.js 4.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350953519535295353953549535595356953579535895359953609536195362953639536495365953669536795368953699537095371953729537395374953759537695377953789537995380953819538295383953849538595386953879538895389953909539195392953939539495395953969539795398953999540095401954029540395404954059540695407954089540995410954119541295413954149541595416954179541895419954209542195422954239542495425954269542795428954299543095431954329543395434954359543695437954389543995440954419544295443954449544595446954479544895449954509545195452954539545495455954569545795458954599546095461954629546395464954659546695467954689546995470954719547295473954749547595476954779547895479954809548195482954839548495485954869548795488954899549095491954929549395494954959549695497954989549995500955019550295503955049550595506955079550895509955109551195512955139551495515955169551795518955199552095521955229552395524955259552695527955289552995530955319553295533955349553595536955379553895539955409554195542955439554495545955469554795548955499555095551955529555395554955559555695557955589555995560955619556295563955649556595566955679556895569955709557195572955739557495575955769557795578955799558095581955829558395584955859558695587955889558995590955919559295593955949559595596955979559895599956009560195602956039560495605956069560795608956099561095611956129561395614956159561695617956189561995620956219562295623956249562595626956279562895629956309563195632956339563495635956369563795638956399564095641956429564395644956459564695647956489564995650956519565295653956549565595656956579565895659956609566195662956639566495665956669566795668956699567095671956729567395674956759567695677956789567995680956819568295683956849568595686956879568895689956909569195692956939569495695956969569795698956999570095701957029570395704957059570695707957089570995710957119571295713957149571595716957179571895719957209572195722957239572495725957269572795728957299573095731957329573395734957359573695737957389573995740957419574295743957449574595746957479574895749957509575195752957539575495755957569575795758957599576095761957629576395764957659576695767957689576995770957719577295773957749577595776957779577895779957809578195782957839578495785957869578795788957899579095791957929579395794957959579695797957989579995800958019580295803958049580595806958079580895809958109581195812958139581495815958169581795818958199582095821958229582395824958259582695827958289582995830958319583295833958349583595836958379583895839958409584195842958439584495845958469584795848958499585095851958529585395854958559585695857958589585995860958619586295863958649586595866958679586895869958709587195872958739587495875958769587795878958799588095881958829588395884958859588695887958889588995890958919589295893958949589595896958979589895899959009590195902959039590495905959069590795908959099591095911959129591395914959159591695917959189591995920959219592295923959249592595926959279592895929959309593195932959339593495935959369593795938959399594095941959429594395944959459594695947959489594995950959519595295953959549595595956959579595895959959609596195962959639596495965959669596795968959699597095971959729597395974959759597695977959789597995980959819598295983959849598595986959879598895989959909599195992959939599495995959969599795998959999600096001960029600396004960059600696007960089600996010960119601296013960149601596016960179601896019960209602196022960239602496025960269602796028960299603096031960329603396034960359603696037960389603996040960419604296043960449604596046960479604896049960509605196052960539605496055960569605796058960599606096061960629606396064960659606696067960689606996070960719607296073960749607596076960779607896079960809608196082960839608496085960869608796088960899609096091960929609396094960959609696097960989609996100961019610296103961049610596106961079610896109961109611196112961139611496115961169611796118961199612096121961229612396124961259612696127961289612996130961319613296133961349613596136961379613896139961409614196142961439614496145961469614796148961499615096151961529615396154961559615696157961589615996160961619616296163961649616596166961679616896169961709617196172961739617496175961769617796178961799618096181961829618396184961859618696187961889618996190961919619296193961949619596196961979619896199962009620196202962039620496205962069620796208962099621096211962129621396214962159621696217962189621996220962219622296223962249622596226962279622896229962309623196232962339623496235962369623796238962399624096241962429624396244962459624696247962489624996250962519625296253962549625596256962579625896259962609626196262962639626496265962669626796268962699627096271962729627396274962759627696277
  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. "use strict";
  31. var BABYLON;
  32. (function (BABYLON) {
  33. /**
  34. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  35. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  36. */
  37. var EffectFallbacks = /** @class */ (function () {
  38. function EffectFallbacks() {
  39. this._defines = {};
  40. this._currentRank = 32;
  41. this._maxRank = -1;
  42. }
  43. /**
  44. * Removes the fallback from the bound mesh.
  45. */
  46. EffectFallbacks.prototype.unBindMesh = function () {
  47. this._mesh = null;
  48. };
  49. /**
  50. * Adds a fallback on the specified property.
  51. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  52. * @param define The name of the define in the shader
  53. */
  54. EffectFallbacks.prototype.addFallback = function (rank, define) {
  55. if (!this._defines[rank]) {
  56. if (rank < this._currentRank) {
  57. this._currentRank = rank;
  58. }
  59. if (rank > this._maxRank) {
  60. this._maxRank = rank;
  61. }
  62. this._defines[rank] = new Array();
  63. }
  64. this._defines[rank].push(define);
  65. };
  66. /**
  67. * Sets the mesh to use CPU skinning when needing to fallback.
  68. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  69. * @param mesh The mesh to use the fallbacks.
  70. */
  71. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  72. this._mesh = mesh;
  73. if (rank < this._currentRank) {
  74. this._currentRank = rank;
  75. }
  76. if (rank > this._maxRank) {
  77. this._maxRank = rank;
  78. }
  79. };
  80. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  81. /**
  82. * Checks to see if more fallbacks are still availible.
  83. */
  84. get: function () {
  85. return this._currentRank <= this._maxRank;
  86. },
  87. enumerable: true,
  88. configurable: true
  89. });
  90. /**
  91. * Removes the defines that shoould be removed when falling back.
  92. * @param currentDefines defines the current define statements for the shader.
  93. * @param effect defines the current effect we try to compile
  94. * @returns The resulting defines with defines of the current rank removed.
  95. */
  96. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  97. // First we try to switch to CPU skinning
  98. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  99. this._mesh.computeBonesUsingShaders = false;
  100. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  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 {
  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. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. this._uniformBuffersNames = {};
  190. this._isReady = false;
  191. this._compilationError = "";
  192. this.name = baseName;
  193. if (attributesNamesOrOptions.attributes) {
  194. var options = attributesNamesOrOptions;
  195. this._engine = uniformsNamesOrEngine;
  196. this._attributesNames = options.attributes;
  197. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  198. this._samplers = options.samplers.slice();
  199. this.defines = options.defines;
  200. this.onError = options.onError;
  201. this.onCompiled = options.onCompiled;
  202. this._fallbacks = options.fallbacks;
  203. this._indexParameters = options.indexParameters;
  204. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  205. if (options.uniformBuffersNames) {
  206. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  207. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  208. }
  209. }
  210. }
  211. else {
  212. this._engine = engine;
  213. this.defines = defines;
  214. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  215. this._samplers = samplers ? samplers.slice() : [];
  216. this._attributesNames = attributesNamesOrOptions;
  217. this.onError = onError;
  218. this.onCompiled = onCompiled;
  219. this._indexParameters = indexParameters;
  220. this._fallbacks = fallbacks;
  221. }
  222. this.uniqueId = Effect._uniqueIdSeed++;
  223. var vertexSource;
  224. var fragmentSource;
  225. if (baseName.vertexElement) {
  226. vertexSource = document.getElementById(baseName.vertexElement);
  227. if (!vertexSource) {
  228. vertexSource = baseName.vertexElement;
  229. }
  230. }
  231. else {
  232. vertexSource = baseName.vertex || baseName;
  233. }
  234. if (baseName.fragmentElement) {
  235. fragmentSource = document.getElementById(baseName.fragmentElement);
  236. if (!fragmentSource) {
  237. fragmentSource = baseName.fragmentElement;
  238. }
  239. }
  240. else {
  241. fragmentSource = baseName.fragment || baseName;
  242. }
  243. this._loadVertexShader(vertexSource, function (vertexCode) {
  244. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  245. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  246. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  247. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  248. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  249. if (baseName) {
  250. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  251. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  252. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  253. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  254. }
  255. else {
  256. _this._vertexSourceCode = migratedVertexCode;
  257. _this._fragmentSourceCode = migratedFragmentCode;
  258. }
  259. _this._prepareEffect();
  260. });
  261. });
  262. });
  263. });
  264. });
  265. });
  266. }
  267. Object.defineProperty(Effect.prototype, "key", {
  268. /**
  269. * Unique key for this effect
  270. */
  271. get: function () {
  272. return this._key;
  273. },
  274. enumerable: true,
  275. configurable: true
  276. });
  277. /**
  278. * If the effect has been compiled and prepared.
  279. * @returns if the effect is compiled and prepared.
  280. */
  281. Effect.prototype.isReady = function () {
  282. return this._isReady;
  283. };
  284. /**
  285. * The engine the effect was initialized with.
  286. * @returns the engine.
  287. */
  288. Effect.prototype.getEngine = function () {
  289. return this._engine;
  290. };
  291. /**
  292. * The compiled webGL program for the effect
  293. * @returns the webGL program.
  294. */
  295. Effect.prototype.getProgram = function () {
  296. return this._program;
  297. };
  298. /**
  299. * The set of names of attribute variables for the shader.
  300. * @returns An array of attribute names.
  301. */
  302. Effect.prototype.getAttributesNames = function () {
  303. return this._attributesNames;
  304. };
  305. /**
  306. * Returns the attribute at the given index.
  307. * @param index The index of the attribute.
  308. * @returns The location of the attribute.
  309. */
  310. Effect.prototype.getAttributeLocation = function (index) {
  311. return this._attributes[index];
  312. };
  313. /**
  314. * Returns the attribute based on the name of the variable.
  315. * @param name of the attribute to look up.
  316. * @returns the attribute location.
  317. */
  318. Effect.prototype.getAttributeLocationByName = function (name) {
  319. var index = this._attributesNames.indexOf(name);
  320. return this._attributes[index];
  321. };
  322. /**
  323. * The number of attributes.
  324. * @returns the numnber of attributes.
  325. */
  326. Effect.prototype.getAttributesCount = function () {
  327. return this._attributes.length;
  328. };
  329. /**
  330. * Gets the index of a uniform variable.
  331. * @param uniformName of the uniform to look up.
  332. * @returns the index.
  333. */
  334. Effect.prototype.getUniformIndex = function (uniformName) {
  335. return this._uniformsNames.indexOf(uniformName);
  336. };
  337. /**
  338. * Returns the attribute based on the name of the variable.
  339. * @param uniformName of the uniform to look up.
  340. * @returns the location of the uniform.
  341. */
  342. Effect.prototype.getUniform = function (uniformName) {
  343. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  344. };
  345. /**
  346. * Returns an array of sampler variable names
  347. * @returns The array of sampler variable neames.
  348. */
  349. Effect.prototype.getSamplers = function () {
  350. return this._samplers;
  351. };
  352. /**
  353. * The error from the last compilation.
  354. * @returns the error string.
  355. */
  356. Effect.prototype.getCompilationError = function () {
  357. return this._compilationError;
  358. };
  359. /**
  360. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  361. * @param func The callback to be used.
  362. */
  363. Effect.prototype.executeWhenCompiled = function (func) {
  364. if (this.isReady()) {
  365. func(this);
  366. return;
  367. }
  368. this.onCompileObservable.add(function (effect) {
  369. func(effect);
  370. });
  371. };
  372. /** @ignore */
  373. Effect.prototype._loadVertexShader = function (vertex, callback) {
  374. if (BABYLON.Tools.IsWindowObjectExist()) {
  375. // DOM element ?
  376. if (vertex instanceof HTMLElement) {
  377. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  378. callback(vertexCode);
  379. return;
  380. }
  381. }
  382. // Base64 encoded ?
  383. if (vertex.substr(0, 7) === "base64:") {
  384. var vertexBinary = window.atob(vertex.substr(7));
  385. callback(vertexBinary);
  386. return;
  387. }
  388. // Is in local store ?
  389. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  390. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  391. return;
  392. }
  393. var vertexShaderUrl;
  394. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  395. vertexShaderUrl = vertex;
  396. }
  397. else {
  398. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  399. }
  400. // Vertex shader
  401. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  402. };
  403. /** @ignore */
  404. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  405. if (BABYLON.Tools.IsWindowObjectExist()) {
  406. // DOM element ?
  407. if (fragment instanceof HTMLElement) {
  408. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  409. callback(fragmentCode);
  410. return;
  411. }
  412. }
  413. // Base64 encoded ?
  414. if (fragment.substr(0, 7) === "base64:") {
  415. var fragmentBinary = window.atob(fragment.substr(7));
  416. callback(fragmentBinary);
  417. return;
  418. }
  419. // Is in local store ?
  420. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  421. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  422. return;
  423. }
  424. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  425. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  426. return;
  427. }
  428. var fragmentShaderUrl;
  429. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  430. fragmentShaderUrl = fragment;
  431. }
  432. else {
  433. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  434. }
  435. // Fragment shader
  436. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  437. };
  438. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  439. // Rebuild shaders source code
  440. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  441. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  442. vertexCode = prefix + vertexCode;
  443. fragmentCode = prefix + fragmentCode;
  444. // Number lines of shaders source code
  445. var i = 2;
  446. var regex = /\n/gm;
  447. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  448. i = 2;
  449. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  450. // Dump shaders name and formatted source code
  451. if (this.name.vertexElement) {
  452. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  453. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  454. }
  455. else if (this.name.vertex) {
  456. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  457. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  458. }
  459. else {
  460. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  461. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  462. }
  463. };
  464. ;
  465. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  466. var preparedSourceCode = this._processPrecision(sourceCode);
  467. if (this._engine.webGLVersion == 1) {
  468. callback(preparedSourceCode);
  469. return;
  470. }
  471. // Already converted
  472. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  473. callback(preparedSourceCode.replace("#version 300 es", ""));
  474. return;
  475. }
  476. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  477. // Remove extensions
  478. // #extension GL_OES_standard_derivatives : enable
  479. // #extension GL_EXT_shader_texture_lod : enable
  480. // #extension GL_EXT_frag_depth : enable
  481. // #extension GL_EXT_draw_buffers : require
  482. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  483. var result = preparedSourceCode.replace(regex, "");
  484. // Migrate to GLSL v300
  485. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  486. result = result.replace(/attribute[ \t]/g, "in ");
  487. result = result.replace(/[ \t]attribute/g, " in");
  488. if (isFragment) {
  489. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  490. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  491. result = result.replace(/texture2D\s*\(/g, "texture(");
  492. result = result.replace(/textureCube\s*\(/g, "texture(");
  493. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  494. result = result.replace(/gl_FragColor/g, "glFragColor");
  495. result = result.replace(/gl_FragData/g, "glFragData");
  496. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  497. }
  498. callback(result);
  499. };
  500. Effect.prototype._processIncludes = function (sourceCode, callback) {
  501. var _this = this;
  502. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  503. var match = regex.exec(sourceCode);
  504. var returnValue = new String(sourceCode);
  505. while (match != null) {
  506. var includeFile = match[1];
  507. // Uniform declaration
  508. if (includeFile.indexOf("__decl__") !== -1) {
  509. includeFile = includeFile.replace(/__decl__/, "");
  510. if (this._engine.supportsUniformBuffers) {
  511. includeFile = includeFile.replace(/Vertex/, "Ubo");
  512. includeFile = includeFile.replace(/Fragment/, "Ubo");
  513. }
  514. includeFile = includeFile + "Declaration";
  515. }
  516. if (Effect.IncludesShadersStore[includeFile]) {
  517. // Substitution
  518. var includeContent = Effect.IncludesShadersStore[includeFile];
  519. if (match[2]) {
  520. var splits = match[3].split(",");
  521. for (var index = 0; index < splits.length; index += 2) {
  522. var source = new RegExp(splits[index], "g");
  523. var dest = splits[index + 1];
  524. includeContent = includeContent.replace(source, dest);
  525. }
  526. }
  527. if (match[4]) {
  528. var indexString = match[5];
  529. if (indexString.indexOf("..") !== -1) {
  530. var indexSplits = indexString.split("..");
  531. var minIndex = parseInt(indexSplits[0]);
  532. var maxIndex = parseInt(indexSplits[1]);
  533. var sourceIncludeContent = includeContent.slice(0);
  534. includeContent = "";
  535. if (isNaN(maxIndex)) {
  536. maxIndex = this._indexParameters[indexSplits[1]];
  537. }
  538. for (var i = minIndex; i < maxIndex; i++) {
  539. if (!this._engine.supportsUniformBuffers) {
  540. // Ubo replacement
  541. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  542. return p1 + "{X}";
  543. });
  544. }
  545. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  546. }
  547. }
  548. else {
  549. if (!this._engine.supportsUniformBuffers) {
  550. // Ubo replacement
  551. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  552. return p1 + "{X}";
  553. });
  554. }
  555. includeContent = includeContent.replace(/\{X\}/g, indexString);
  556. }
  557. }
  558. // Replace
  559. returnValue = returnValue.replace(match[0], includeContent);
  560. }
  561. else {
  562. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  563. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  564. Effect.IncludesShadersStore[includeFile] = fileContent;
  565. _this._processIncludes(returnValue, callback);
  566. });
  567. return;
  568. }
  569. match = regex.exec(sourceCode);
  570. }
  571. callback(returnValue);
  572. };
  573. Effect.prototype._processPrecision = function (source) {
  574. if (source.indexOf("precision highp float") === -1) {
  575. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  576. source = "precision mediump float;\n" + source;
  577. }
  578. else {
  579. source = "precision highp float;\n" + source;
  580. }
  581. }
  582. else {
  583. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  584. source = source.replace("precision highp float", "precision mediump float");
  585. }
  586. }
  587. return source;
  588. };
  589. /**
  590. * Recompiles the webGL program
  591. * @param vertexSourceCode The source code for the vertex shader.
  592. * @param fragmentSourceCode The source code for the fragment shader.
  593. * @param onCompiled Callback called when completed.
  594. * @param onError Callback called on error.
  595. */
  596. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  597. var _this = this;
  598. this._isReady = false;
  599. this._vertexSourceCodeOverride = vertexSourceCode;
  600. this._fragmentSourceCodeOverride = fragmentSourceCode;
  601. this.onError = function (effect, error) {
  602. if (onError) {
  603. onError(error);
  604. }
  605. };
  606. this.onCompiled = function () {
  607. var scenes = _this.getEngine().scenes;
  608. for (var i = 0; i < scenes.length; i++) {
  609. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  610. }
  611. if (onCompiled) {
  612. onCompiled(_this._program);
  613. }
  614. };
  615. this._fallbacks = null;
  616. this._prepareEffect();
  617. };
  618. /**
  619. * Gets the uniform locations of the the specified variable names
  620. * @param names THe names of the variables to lookup.
  621. * @returns Array of locations in the same order as variable names.
  622. */
  623. Effect.prototype.getSpecificUniformLocations = function (names) {
  624. var engine = this._engine;
  625. return engine.getUniforms(this._program, names);
  626. };
  627. /**
  628. * Prepares the effect
  629. */
  630. Effect.prototype._prepareEffect = function () {
  631. var attributesNames = this._attributesNames;
  632. var defines = this.defines;
  633. var fallbacks = this._fallbacks;
  634. this._valueCache = {};
  635. var previousProgram = this._program;
  636. try {
  637. var engine = this._engine;
  638. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  639. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  640. }
  641. else {
  642. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  643. }
  644. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  645. if (engine.supportsUniformBuffers) {
  646. for (var name in this._uniformBuffersNames) {
  647. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  648. }
  649. }
  650. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  651. this._attributes = engine.getAttributes(this._program, attributesNames);
  652. var index;
  653. for (index = 0; index < this._samplers.length; index++) {
  654. var sampler = this.getUniform(this._samplers[index]);
  655. if (sampler == null) {
  656. this._samplers.splice(index, 1);
  657. index--;
  658. }
  659. }
  660. engine.bindSamplers(this);
  661. this._compilationError = "";
  662. this._isReady = true;
  663. if (this.onCompiled) {
  664. this.onCompiled(this);
  665. }
  666. this.onCompileObservable.notifyObservers(this);
  667. this.onCompileObservable.clear();
  668. // Unbind mesh reference in fallbacks
  669. if (this._fallbacks) {
  670. this._fallbacks.unBindMesh();
  671. }
  672. if (previousProgram) {
  673. this.getEngine()._deleteProgram(previousProgram);
  674. }
  675. }
  676. catch (e) {
  677. this._compilationError = e.message;
  678. // Let's go through fallbacks then
  679. BABYLON.Tools.Error("Unable to compile effect:");
  680. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  681. return " " + uniform;
  682. }));
  683. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  684. return " " + attribute;
  685. }));
  686. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  687. BABYLON.Tools.Error("Error: " + this._compilationError);
  688. if (previousProgram) {
  689. this._program = previousProgram;
  690. this._isReady = true;
  691. if (this.onError) {
  692. this.onError(this, this._compilationError);
  693. }
  694. this.onErrorObservable.notifyObservers(this);
  695. }
  696. if (fallbacks && fallbacks.isMoreFallbacks) {
  697. BABYLON.Tools.Error("Trying next fallback.");
  698. this.defines = fallbacks.reduce(this.defines, this);
  699. this._prepareEffect();
  700. }
  701. else {
  702. if (this.onError) {
  703. this.onError(this, this._compilationError);
  704. }
  705. this.onErrorObservable.notifyObservers(this);
  706. this.onErrorObservable.clear();
  707. // Unbind mesh reference in fallbacks
  708. if (this._fallbacks) {
  709. this._fallbacks.unBindMesh();
  710. }
  711. }
  712. }
  713. };
  714. Object.defineProperty(Effect.prototype, "isSupported", {
  715. /**
  716. * Checks if the effect is supported. (Must be called after compilation)
  717. */
  718. get: function () {
  719. return this._compilationError === "";
  720. },
  721. enumerable: true,
  722. configurable: true
  723. });
  724. /**
  725. * Binds a texture to the engine to be used as output of the shader.
  726. * @param channel Name of the output variable.
  727. * @param texture Texture to bind.
  728. */
  729. Effect.prototype._bindTexture = function (channel, texture) {
  730. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  731. };
  732. /**
  733. * Sets a texture on the engine to be used in the shader.
  734. * @param channel Name of the sampler variable.
  735. * @param texture Texture to set.
  736. */
  737. Effect.prototype.setTexture = function (channel, texture) {
  738. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  739. };
  740. /**
  741. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  742. * @param channel Name of the sampler variable.
  743. * @param texture Texture to set.
  744. */
  745. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  746. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  747. };
  748. /**
  749. * Sets an array of textures on the engine to be used in the shader.
  750. * @param channel Name of the variable.
  751. * @param textures Textures to set.
  752. */
  753. Effect.prototype.setTextureArray = function (channel, textures) {
  754. if (this._samplers.indexOf(channel + "Ex") === -1) {
  755. var initialPos = this._samplers.indexOf(channel);
  756. for (var index = 1; index < textures.length; index++) {
  757. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  758. }
  759. }
  760. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  761. };
  762. /**
  763. * 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)
  764. * @param channel Name of the sampler variable.
  765. * @param postProcess Post process to get the input texture from.
  766. */
  767. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  768. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  769. };
  770. /**
  771. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  772. * 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)
  773. * @param channel Name of the sampler variable.
  774. * @param postProcess Post process to get the output texture from.
  775. */
  776. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  777. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  778. };
  779. /** @ignore */
  780. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  781. var cache = this._valueCache[uniformName];
  782. var flag = matrix.updateFlag;
  783. if (cache !== undefined && cache === flag) {
  784. return false;
  785. }
  786. this._valueCache[uniformName] = flag;
  787. return true;
  788. };
  789. /** @ignore */
  790. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  791. var cache = this._valueCache[uniformName];
  792. if (!cache) {
  793. cache = [x, y];
  794. this._valueCache[uniformName] = cache;
  795. return true;
  796. }
  797. var changed = false;
  798. if (cache[0] !== x) {
  799. cache[0] = x;
  800. changed = true;
  801. }
  802. if (cache[1] !== y) {
  803. cache[1] = y;
  804. changed = true;
  805. }
  806. return changed;
  807. };
  808. /** @ignore */
  809. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  810. var cache = this._valueCache[uniformName];
  811. if (!cache) {
  812. cache = [x, y, z];
  813. this._valueCache[uniformName] = cache;
  814. return true;
  815. }
  816. var changed = false;
  817. if (cache[0] !== x) {
  818. cache[0] = x;
  819. changed = true;
  820. }
  821. if (cache[1] !== y) {
  822. cache[1] = y;
  823. changed = true;
  824. }
  825. if (cache[2] !== z) {
  826. cache[2] = z;
  827. changed = true;
  828. }
  829. return changed;
  830. };
  831. /** @ignore */
  832. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  833. var cache = this._valueCache[uniformName];
  834. if (!cache) {
  835. cache = [x, y, z, w];
  836. this._valueCache[uniformName] = cache;
  837. return true;
  838. }
  839. var changed = false;
  840. if (cache[0] !== x) {
  841. cache[0] = x;
  842. changed = true;
  843. }
  844. if (cache[1] !== y) {
  845. cache[1] = y;
  846. changed = true;
  847. }
  848. if (cache[2] !== z) {
  849. cache[2] = z;
  850. changed = true;
  851. }
  852. if (cache[3] !== w) {
  853. cache[3] = w;
  854. changed = true;
  855. }
  856. return changed;
  857. };
  858. /**
  859. * Binds a buffer to a uniform.
  860. * @param buffer Buffer to bind.
  861. * @param name Name of the uniform variable to bind to.
  862. */
  863. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  864. var bufferName = this._uniformBuffersNames[name];
  865. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  866. return;
  867. }
  868. Effect._baseCache[bufferName] = buffer;
  869. this._engine.bindUniformBufferBase(buffer, bufferName);
  870. };
  871. /**
  872. * Binds block to a uniform.
  873. * @param blockName Name of the block to bind.
  874. * @param index Index to bind.
  875. */
  876. Effect.prototype.bindUniformBlock = function (blockName, index) {
  877. this._engine.bindUniformBlock(this._program, blockName, index);
  878. };
  879. /**
  880. * Sets an interger value on a uniform variable.
  881. * @param uniformName Name of the variable.
  882. * @param value Value to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setInt = function (uniformName, value) {
  886. var cache = this._valueCache[uniformName];
  887. if (cache !== undefined && cache === value)
  888. return this;
  889. this._valueCache[uniformName] = value;
  890. this._engine.setInt(this.getUniform(uniformName), value);
  891. return this;
  892. };
  893. /**
  894. * Sets an int array on a uniform variable.
  895. * @param uniformName Name of the variable.
  896. * @param array array to be set.
  897. * @returns this effect.
  898. */
  899. Effect.prototype.setIntArray = function (uniformName, array) {
  900. this._valueCache[uniformName] = null;
  901. this._engine.setIntArray(this.getUniform(uniformName), array);
  902. return this;
  903. };
  904. /**
  905. * 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)
  906. * @param uniformName Name of the variable.
  907. * @param array array to be set.
  908. * @returns this effect.
  909. */
  910. Effect.prototype.setIntArray2 = function (uniformName, array) {
  911. this._valueCache[uniformName] = null;
  912. this._engine.setIntArray2(this.getUniform(uniformName), array);
  913. return this;
  914. };
  915. /**
  916. * 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)
  917. * @param uniformName Name of the variable.
  918. * @param array array to be set.
  919. * @returns this effect.
  920. */
  921. Effect.prototype.setIntArray3 = function (uniformName, array) {
  922. this._valueCache[uniformName] = null;
  923. this._engine.setIntArray3(this.getUniform(uniformName), array);
  924. return this;
  925. };
  926. /**
  927. * 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)
  928. * @param uniformName Name of the variable.
  929. * @param array array to be set.
  930. * @returns this effect.
  931. */
  932. Effect.prototype.setIntArray4 = function (uniformName, array) {
  933. this._valueCache[uniformName] = null;
  934. this._engine.setIntArray4(this.getUniform(uniformName), array);
  935. return this;
  936. };
  937. /**
  938. * Sets an float array on a uniform variable.
  939. * @param uniformName Name of the variable.
  940. * @param array array to be set.
  941. * @returns this effect.
  942. */
  943. Effect.prototype.setFloatArray = function (uniformName, array) {
  944. this._valueCache[uniformName] = null;
  945. this._engine.setFloatArray(this.getUniform(uniformName), array);
  946. return this;
  947. };
  948. /**
  949. * 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)
  950. * @param uniformName Name of the variable.
  951. * @param array array to be set.
  952. * @returns this effect.
  953. */
  954. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  955. this._valueCache[uniformName] = null;
  956. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  957. return this;
  958. };
  959. /**
  960. * 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)
  961. * @param uniformName Name of the variable.
  962. * @param array array to be set.
  963. * @returns this effect.
  964. */
  965. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  966. this._valueCache[uniformName] = null;
  967. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  968. return this;
  969. };
  970. /**
  971. * 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)
  972. * @param uniformName Name of the variable.
  973. * @param array array to be set.
  974. * @returns this effect.
  975. */
  976. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  977. this._valueCache[uniformName] = null;
  978. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  979. return this;
  980. };
  981. /**
  982. * Sets an array on a uniform variable.
  983. * @param uniformName Name of the variable.
  984. * @param array array to be set.
  985. * @returns this effect.
  986. */
  987. Effect.prototype.setArray = function (uniformName, array) {
  988. this._valueCache[uniformName] = null;
  989. this._engine.setArray(this.getUniform(uniformName), array);
  990. return this;
  991. };
  992. /**
  993. * 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)
  994. * @param uniformName Name of the variable.
  995. * @param array array to be set.
  996. * @returns this effect.
  997. */
  998. Effect.prototype.setArray2 = function (uniformName, array) {
  999. this._valueCache[uniformName] = null;
  1000. this._engine.setArray2(this.getUniform(uniformName), array);
  1001. return this;
  1002. };
  1003. /**
  1004. * 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)
  1005. * @param uniformName Name of the variable.
  1006. * @param array array to be set.
  1007. * @returns this effect.
  1008. */
  1009. Effect.prototype.setArray3 = function (uniformName, array) {
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setArray3(this.getUniform(uniformName), array);
  1012. return this;
  1013. };
  1014. /**
  1015. * 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)
  1016. * @param uniformName Name of the variable.
  1017. * @param array array to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setArray4 = function (uniformName, array) {
  1021. this._valueCache[uniformName] = null;
  1022. this._engine.setArray4(this.getUniform(uniformName), array);
  1023. return this;
  1024. };
  1025. /**
  1026. * Sets matrices on a uniform variable.
  1027. * @param uniformName Name of the variable.
  1028. * @param matrices matrices to be set.
  1029. * @returns this effect.
  1030. */
  1031. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1032. if (!matrices) {
  1033. return this;
  1034. }
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrix on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrix matrix to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1046. if (this._cacheMatrix(uniformName, matrix)) {
  1047. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1048. }
  1049. return this;
  1050. };
  1051. /**
  1052. * 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)
  1053. * @param uniformName Name of the variable.
  1054. * @param matrix matrix to be set.
  1055. * @returns this effect.
  1056. */
  1057. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1058. this._valueCache[uniformName] = null;
  1059. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1064. * @param uniformName Name of the variable.
  1065. * @param matrix matrix to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1069. this._valueCache[uniformName] = null;
  1070. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets a float on a uniform variable.
  1075. * @param uniformName Name of the variable.
  1076. * @param value value to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setFloat = function (uniformName, value) {
  1080. var cache = this._valueCache[uniformName];
  1081. if (cache !== undefined && cache === value)
  1082. return this;
  1083. this._valueCache[uniformName] = value;
  1084. this._engine.setFloat(this.getUniform(uniformName), value);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a boolean on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param bool value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setBool = function (uniformName, bool) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === bool)
  1096. return this;
  1097. this._valueCache[uniformName] = bool;
  1098. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector2 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector2 vector2 to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1108. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float2 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float2.
  1117. * @param y Second float in float2.
  1118. * @returns this effect.
  1119. */
  1120. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1121. if (this._cacheFloat2(uniformName, x, y)) {
  1122. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1123. }
  1124. return this;
  1125. };
  1126. /**
  1127. * Sets a Vector3 on a uniform variable.
  1128. * @param uniformName Name of the variable.
  1129. * @param vector3 Value to be set.
  1130. * @returns this effect.
  1131. */
  1132. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1133. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1134. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1135. }
  1136. return this;
  1137. };
  1138. /**
  1139. * Sets a float3 on a uniform variable.
  1140. * @param uniformName Name of the variable.
  1141. * @param x First float in float3.
  1142. * @param y Second float in float3.
  1143. * @param z Third float in float3.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1147. if (this._cacheFloat3(uniformName, x, y, z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a Vector4 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param vector4 Value to be set.
  1156. * @returns this effect.
  1157. */
  1158. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1159. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1160. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1161. }
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a float4 on a uniform variable.
  1166. * @param uniformName Name of the variable.
  1167. * @param x First float in float4.
  1168. * @param y Second float in float4.
  1169. * @param z Third float in float4.
  1170. * @param w Fourth float in float4.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1174. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1175. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color3 on a uniform variable.
  1181. * @param uniformName Name of the variable.
  1182. * @param color3 Value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor3 = function (uniformName, color3) {
  1186. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1187. this._engine.setColor3(this.getUniform(uniformName), color3);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable.
  1193. * @param uniformName Name of the variable.
  1194. * @param color3 Value to be set.
  1195. * @param alpha Alpha value to be set.
  1196. * @returns this effect.
  1197. */
  1198. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1199. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1200. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1201. }
  1202. return this;
  1203. };
  1204. /**
  1205. * Sets a Color4 on a uniform variable
  1206. * @param uniformName defines the name of the variable
  1207. * @param color4 defines the value to be set
  1208. * @returns this effect.
  1209. */
  1210. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1211. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1212. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1213. }
  1214. return this;
  1215. };
  1216. /**
  1217. * Resets the cache of effects.
  1218. */
  1219. Effect.ResetCache = function () {
  1220. Effect._baseCache = {};
  1221. };
  1222. Effect._uniqueIdSeed = 0;
  1223. Effect._baseCache = {};
  1224. /**
  1225. * Store of each shader (The can be looked up using effect.key)
  1226. */
  1227. Effect.ShadersStore = {};
  1228. /**
  1229. * Store of each included file for a shader (The can be looked up using effect.key)
  1230. */
  1231. Effect.IncludesShadersStore = {};
  1232. return Effect;
  1233. }());
  1234. BABYLON.Effect = Effect;
  1235. })(BABYLON || (BABYLON = {}));
  1236. //# sourceMappingURL=babylon.effect.js.map
  1237. "use strict";
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. "use strict";
  1240. var BABYLON;
  1241. (function (BABYLON) {
  1242. var KeyboardEventTypes = /** @class */ (function () {
  1243. function KeyboardEventTypes() {
  1244. }
  1245. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1246. get: function () {
  1247. return KeyboardEventTypes._KEYDOWN;
  1248. },
  1249. enumerable: true,
  1250. configurable: true
  1251. });
  1252. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1253. get: function () {
  1254. return KeyboardEventTypes._KEYUP;
  1255. },
  1256. enumerable: true,
  1257. configurable: true
  1258. });
  1259. KeyboardEventTypes._KEYDOWN = 0x01;
  1260. KeyboardEventTypes._KEYUP = 0x02;
  1261. return KeyboardEventTypes;
  1262. }());
  1263. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1264. var KeyboardInfo = /** @class */ (function () {
  1265. function KeyboardInfo(type, event) {
  1266. this.type = type;
  1267. this.event = event;
  1268. }
  1269. return KeyboardInfo;
  1270. }());
  1271. BABYLON.KeyboardInfo = KeyboardInfo;
  1272. /**
  1273. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1274. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1275. */
  1276. var KeyboardInfoPre = /** @class */ (function (_super) {
  1277. __extends(KeyboardInfoPre, _super);
  1278. function KeyboardInfoPre(type, event) {
  1279. var _this = _super.call(this, type, event) || this;
  1280. _this.skipOnPointerObservable = false;
  1281. return _this;
  1282. }
  1283. return KeyboardInfoPre;
  1284. }(KeyboardInfo));
  1285. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1286. })(BABYLON || (BABYLON = {}));
  1287. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1288. "use strict";
  1289. var BABYLON;
  1290. (function (BABYLON) {
  1291. var PointerEventTypes = /** @class */ (function () {
  1292. function PointerEventTypes() {
  1293. }
  1294. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERDOWN;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERUP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERMOVE;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1316. get: function () {
  1317. return PointerEventTypes._POINTERWHEEL;
  1318. },
  1319. enumerable: true,
  1320. configurable: true
  1321. });
  1322. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1323. get: function () {
  1324. return PointerEventTypes._POINTERPICK;
  1325. },
  1326. enumerable: true,
  1327. configurable: true
  1328. });
  1329. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1330. get: function () {
  1331. return PointerEventTypes._POINTERTAP;
  1332. },
  1333. enumerable: true,
  1334. configurable: true
  1335. });
  1336. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1337. get: function () {
  1338. return PointerEventTypes._POINTERDOUBLETAP;
  1339. },
  1340. enumerable: true,
  1341. configurable: true
  1342. });
  1343. PointerEventTypes._POINTERDOWN = 0x01;
  1344. PointerEventTypes._POINTERUP = 0x02;
  1345. PointerEventTypes._POINTERMOVE = 0x04;
  1346. PointerEventTypes._POINTERWHEEL = 0x08;
  1347. PointerEventTypes._POINTERPICK = 0x10;
  1348. PointerEventTypes._POINTERTAP = 0x20;
  1349. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1350. return PointerEventTypes;
  1351. }());
  1352. BABYLON.PointerEventTypes = PointerEventTypes;
  1353. var PointerInfoBase = /** @class */ (function () {
  1354. function PointerInfoBase(type, event) {
  1355. this.type = type;
  1356. this.event = event;
  1357. }
  1358. return PointerInfoBase;
  1359. }());
  1360. BABYLON.PointerInfoBase = PointerInfoBase;
  1361. /**
  1362. * This class is used to store pointer related info for the onPrePointerObservable event.
  1363. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1364. */
  1365. var PointerInfoPre = /** @class */ (function (_super) {
  1366. __extends(PointerInfoPre, _super);
  1367. function PointerInfoPre(type, event, localX, localY) {
  1368. var _this = _super.call(this, type, event) || this;
  1369. _this.skipOnPointerObservable = false;
  1370. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1371. return _this;
  1372. }
  1373. return PointerInfoPre;
  1374. }(PointerInfoBase));
  1375. BABYLON.PointerInfoPre = PointerInfoPre;
  1376. /**
  1377. * This type contains all the data related to a pointer event in Babylon.js.
  1378. * 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.
  1379. */
  1380. var PointerInfo = /** @class */ (function (_super) {
  1381. __extends(PointerInfo, _super);
  1382. function PointerInfo(type, event, pickInfo) {
  1383. var _this = _super.call(this, type, event) || this;
  1384. _this.pickInfo = pickInfo;
  1385. return _this;
  1386. }
  1387. return PointerInfo;
  1388. }(PointerInfoBase));
  1389. BABYLON.PointerInfo = PointerInfo;
  1390. })(BABYLON || (BABYLON = {}));
  1391. //# sourceMappingURL=babylon.pointerEvents.js.map
  1392. "use strict";
  1393. var BABYLON;
  1394. (function (BABYLON) {
  1395. BABYLON.ToGammaSpace = 1 / 2.2;
  1396. BABYLON.ToLinearSpace = 2.2;
  1397. BABYLON.Epsilon = 0.001;
  1398. /**
  1399. * Class used to hold a RBG color
  1400. */
  1401. var Color3 = /** @class */ (function () {
  1402. /**
  1403. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1404. * @param r defines the red component (between 0 and 1, default is 0)
  1405. * @param g defines the green component (between 0 and 1, default is 0)
  1406. * @param b defines the blue component (between 0 and 1, default is 0)
  1407. */
  1408. function Color3(
  1409. /**
  1410. * Defines the red component (between 0 and 1, default is 0)
  1411. */
  1412. r,
  1413. /**
  1414. * Defines the green component (between 0 and 1, default is 0)
  1415. */
  1416. g,
  1417. /**
  1418. * Defines the blue component (between 0 and 1, default is 0)
  1419. */
  1420. b) {
  1421. if (r === void 0) { r = 0; }
  1422. if (g === void 0) { g = 0; }
  1423. if (b === void 0) { b = 0; }
  1424. this.r = r;
  1425. this.g = g;
  1426. this.b = b;
  1427. }
  1428. /**
  1429. * Creates a string with the Color3 current values
  1430. * @returns the string representation of the Color3 object
  1431. */
  1432. Color3.prototype.toString = function () {
  1433. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1434. };
  1435. /**
  1436. * Returns the string "Color3"
  1437. * @returns "Color3"
  1438. */
  1439. Color3.prototype.getClassName = function () {
  1440. return "Color3";
  1441. };
  1442. /**
  1443. * Compute the Color3 hash code
  1444. * @returns an unique number that can be used to hash Color3 objects
  1445. */
  1446. Color3.prototype.getHashCode = function () {
  1447. var hash = this.r || 0;
  1448. hash = (hash * 397) ^ (this.g || 0);
  1449. hash = (hash * 397) ^ (this.b || 0);
  1450. return hash;
  1451. };
  1452. // Operators
  1453. /**
  1454. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1455. * @param array defines the array where to store the r,g,b components
  1456. * @param index defines an optional index in the target array to define where to start storing values
  1457. * @returns the current Color3 object
  1458. */
  1459. Color3.prototype.toArray = function (array, index) {
  1460. if (index === undefined) {
  1461. index = 0;
  1462. }
  1463. array[index] = this.r;
  1464. array[index + 1] = this.g;
  1465. array[index + 2] = this.b;
  1466. return this;
  1467. };
  1468. /**
  1469. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1470. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1471. * @returns a new {BABYLON.Color4} object
  1472. */
  1473. Color3.prototype.toColor4 = function (alpha) {
  1474. if (alpha === void 0) { alpha = 1; }
  1475. return new Color4(this.r, this.g, this.b, alpha);
  1476. };
  1477. /**
  1478. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1479. * @returns the new array
  1480. */
  1481. Color3.prototype.asArray = function () {
  1482. var result = new Array();
  1483. this.toArray(result, 0);
  1484. return result;
  1485. };
  1486. /**
  1487. * Returns the luminance value
  1488. * @returns a float value
  1489. */
  1490. Color3.prototype.toLuminance = function () {
  1491. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1492. };
  1493. /**
  1494. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1495. * @param otherColor defines the second operand
  1496. * @returns the new Color3 object
  1497. */
  1498. Color3.prototype.multiply = function (otherColor) {
  1499. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1500. };
  1501. /**
  1502. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1503. * @param otherColor defines the second operand
  1504. * @param result defines the Color3 object where to store the result
  1505. * @returns the current Color3
  1506. */
  1507. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1508. result.r = this.r * otherColor.r;
  1509. result.g = this.g * otherColor.g;
  1510. result.b = this.b * otherColor.b;
  1511. return this;
  1512. };
  1513. /**
  1514. * Determines equality between Color3 objects
  1515. * @param otherColor defines the second operand
  1516. * @returns true if the rgb values are equal to the passed ones
  1517. */
  1518. Color3.prototype.equals = function (otherColor) {
  1519. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1520. };
  1521. /**
  1522. * Determines equality between the current Color3 object and a set of r,b,g values
  1523. * @param r defines the red component to check
  1524. * @param g defines the green component to check
  1525. * @param b defines the blue component to check
  1526. * @returns true if the rgb values are equal to the passed ones
  1527. */
  1528. Color3.prototype.equalsFloats = function (r, g, b) {
  1529. return this.r === r && this.g === g && this.b === b;
  1530. };
  1531. /**
  1532. * Multiplies in place each rgb value by scale
  1533. * @param scale defines the scaling factor
  1534. * @returns the updated Color3
  1535. */
  1536. Color3.prototype.scale = function (scale) {
  1537. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1538. };
  1539. /**
  1540. * Multiplies the rgb values by scale and stores the result into "result"
  1541. * @param scale defines the scaling factor
  1542. * @param result defines the Color3 object where to store the result
  1543. * @returns the unmodified current Color3
  1544. */
  1545. Color3.prototype.scaleToRef = function (scale, result) {
  1546. result.r = this.r * scale;
  1547. result.g = this.g * scale;
  1548. result.b = this.b * scale;
  1549. return this;
  1550. };
  1551. /**
  1552. * Scale the current Color3 values by a factor and add the result to a given Color3
  1553. * @param scale defines the scale factor
  1554. * @param result defines color to store the result into
  1555. * @returns the unmodified current Color3
  1556. */
  1557. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1558. result.r += this.r * scale;
  1559. result.g += this.g * scale;
  1560. result.b += this.b * scale;
  1561. return this;
  1562. };
  1563. /**
  1564. * Clamps the rgb values by the min and max values and stores the result into "result"
  1565. * @param min defines minimum clamping value (default is 0)
  1566. * @param max defines maximum clamping value (default is 1)
  1567. * @param result defines color to store the result into
  1568. * @returns the original Color3
  1569. */
  1570. Color3.prototype.clampToRef = function (min, max, result) {
  1571. if (min === void 0) { min = 0; }
  1572. if (max === void 0) { max = 1; }
  1573. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1574. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1575. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1576. return this;
  1577. };
  1578. /**
  1579. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1580. * @param otherColor defines the second operand
  1581. * @returns the new Color3
  1582. */
  1583. Color3.prototype.add = function (otherColor) {
  1584. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1585. };
  1586. /**
  1587. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1588. * @param otherColor defines the second operand
  1589. * @param result defines Color3 object to store the result into
  1590. * @returns the unmodified current Color3
  1591. */
  1592. Color3.prototype.addToRef = function (otherColor, result) {
  1593. result.r = this.r + otherColor.r;
  1594. result.g = this.g + otherColor.g;
  1595. result.b = this.b + otherColor.b;
  1596. return this;
  1597. };
  1598. /**
  1599. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1600. * @param otherColor defines the second operand
  1601. * @returns the new Color3
  1602. */
  1603. Color3.prototype.subtract = function (otherColor) {
  1604. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1605. };
  1606. /**
  1607. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1608. * @param otherColor defines the second operand
  1609. * @param result defines Color3 object to store the result into
  1610. * @returns the unmodified current Color3
  1611. */
  1612. Color3.prototype.subtractToRef = function (otherColor, result) {
  1613. result.r = this.r - otherColor.r;
  1614. result.g = this.g - otherColor.g;
  1615. result.b = this.b - otherColor.b;
  1616. return this;
  1617. };
  1618. /**
  1619. * Copy the current object
  1620. * @returns a new Color3 copied the current one
  1621. */
  1622. Color3.prototype.clone = function () {
  1623. return new Color3(this.r, this.g, this.b);
  1624. };
  1625. /**
  1626. * Copies the rgb values from the source in the current Color3
  1627. * @param source defines the source Color3 object
  1628. * @returns the updated Color3 object
  1629. */
  1630. Color3.prototype.copyFrom = function (source) {
  1631. this.r = source.r;
  1632. this.g = source.g;
  1633. this.b = source.b;
  1634. return this;
  1635. };
  1636. /**
  1637. * Updates the Color3 rgb values from the passed floats
  1638. * @param r defines the red component to read from
  1639. * @param g defines the green component to read from
  1640. * @param b defines the blue component to read from
  1641. * @returns the current Color3 object
  1642. */
  1643. Color3.prototype.copyFromFloats = function (r, g, b) {
  1644. this.r = r;
  1645. this.g = g;
  1646. this.b = b;
  1647. return this;
  1648. };
  1649. /**
  1650. * Updates the Color3 rgb values from the passed floats
  1651. * @param r defines the red component to read from
  1652. * @param g defines the green component to read from
  1653. * @param b defines the blue component to read from
  1654. * @returns the current Color3 object
  1655. */
  1656. Color3.prototype.set = function (r, g, b) {
  1657. return this.copyFromFloats(r, g, b);
  1658. };
  1659. /**
  1660. * Compute the Color3 hexadecimal code as a string
  1661. * @returns a string containing the hexadecimal representation of the Color3 object
  1662. */
  1663. Color3.prototype.toHexString = function () {
  1664. var intR = (this.r * 255) | 0;
  1665. var intG = (this.g * 255) | 0;
  1666. var intB = (this.b * 255) | 0;
  1667. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1668. };
  1669. /**
  1670. * Computes a new Color3 converted from the current one to linear space
  1671. * @returns a new Color3 object
  1672. */
  1673. Color3.prototype.toLinearSpace = function () {
  1674. var convertedColor = new Color3();
  1675. this.toLinearSpaceToRef(convertedColor);
  1676. return convertedColor;
  1677. };
  1678. /**
  1679. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1680. * @param convertedColor defines the Color3 object where to store the linear space version
  1681. * @returns the unmodified Color3
  1682. */
  1683. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1684. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1685. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1686. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1687. return this;
  1688. };
  1689. /**
  1690. * Computes a new Color3 converted from the current one to gamma space
  1691. * @returns a new Color3 object
  1692. */
  1693. Color3.prototype.toGammaSpace = function () {
  1694. var convertedColor = new Color3();
  1695. this.toGammaSpaceToRef(convertedColor);
  1696. return convertedColor;
  1697. };
  1698. /**
  1699. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1700. * @param convertedColor defines the Color3 object where to store the gamma space version
  1701. * @returns the unmodified Color3
  1702. */
  1703. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1704. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1705. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1706. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1707. return this;
  1708. };
  1709. // Statics
  1710. /**
  1711. * Creates a new Color3 from the string containing valid hexadecimal values
  1712. * @param hex defines a string containing valid hexadecimal values
  1713. * @returns a new Color3 object
  1714. */
  1715. Color3.FromHexString = function (hex) {
  1716. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1717. return new Color3(0, 0, 0);
  1718. }
  1719. var r = parseInt(hex.substring(1, 3), 16);
  1720. var g = parseInt(hex.substring(3, 5), 16);
  1721. var b = parseInt(hex.substring(5, 7), 16);
  1722. return Color3.FromInts(r, g, b);
  1723. };
  1724. /**
  1725. * Creates a new Vector3 from the starting index of the passed array
  1726. * @param array defines the source array
  1727. * @param offset defines an offset in the source array
  1728. * @returns a new Color3 object
  1729. */
  1730. Color3.FromArray = function (array, offset) {
  1731. if (offset === void 0) { offset = 0; }
  1732. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1733. };
  1734. /**
  1735. * Creates a new Color3 from integer values (< 256)
  1736. * @param r defines the red component to read from (value between 0 and 255)
  1737. * @param g defines the green component to read from (value between 0 and 255)
  1738. * @param b defines the blue component to read from (value between 0 and 255)
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.FromInts = function (r, g, b) {
  1742. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1743. };
  1744. /**
  1745. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1746. * @param start defines the start Color3 value
  1747. * @param end defines the end Color3 value
  1748. * @param amount defines the gradient value between start and end
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Lerp = function (start, end, amount) {
  1752. var r = start.r + ((end.r - start.r) * amount);
  1753. var g = start.g + ((end.g - start.g) * amount);
  1754. var b = start.b + ((end.b - start.b) * amount);
  1755. return new Color3(r, g, b);
  1756. };
  1757. /**
  1758. * Returns a Color3 value containing a red color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Red = function () { return new Color3(1, 0, 0); };
  1762. /**
  1763. * Returns a Color3 value containing a green color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Green = function () { return new Color3(0, 1, 0); };
  1767. /**
  1768. * Returns a Color3 value containing a blue color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1772. /**
  1773. * Returns a Color3 value containing a black color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Black = function () { return new Color3(0, 0, 0); };
  1777. /**
  1778. * Returns a Color3 value containing a white color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.White = function () { return new Color3(1, 1, 1); };
  1782. /**
  1783. * Returns a Color3 value containing a purple color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1787. /**
  1788. * Returns a Color3 value containing a magenta color
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1792. /**
  1793. * Returns a Color3 value containing a yellow color
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1797. /**
  1798. * Returns a Color3 value containing a gray color
  1799. * @returns a new Color3 object
  1800. */
  1801. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1802. /**
  1803. * Returns a Color3 value containing a teal color
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1807. /**
  1808. * Returns a Color3 value containing a random color
  1809. * @returns a new Color3 object
  1810. */
  1811. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1812. return Color3;
  1813. }());
  1814. BABYLON.Color3 = Color3;
  1815. /**
  1816. * Class used to hold a RBGA color
  1817. */
  1818. var Color4 = /** @class */ (function () {
  1819. /**
  1820. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1821. * @param r defines the red component (between 0 and 1, default is 0)
  1822. * @param g defines the green component (between 0 and 1, default is 0)
  1823. * @param b defines the blue component (between 0 and 1, default is 0)
  1824. * @param a defines the alpha component (between 0 and 1, default is 1)
  1825. */
  1826. function Color4(
  1827. /**
  1828. * Defines the red component (between 0 and 1, default is 0)
  1829. */
  1830. r,
  1831. /**
  1832. * Defines the green component (between 0 and 1, default is 0)
  1833. */
  1834. g,
  1835. /**
  1836. * Defines the blue component (between 0 and 1, default is 0)
  1837. */
  1838. b,
  1839. /**
  1840. * Defines the alpha component (between 0 and 1, default is 1)
  1841. */
  1842. a) {
  1843. if (r === void 0) { r = 0; }
  1844. if (g === void 0) { g = 0; }
  1845. if (b === void 0) { b = 0; }
  1846. if (a === void 0) { a = 1; }
  1847. this.r = r;
  1848. this.g = g;
  1849. this.b = b;
  1850. this.a = a;
  1851. }
  1852. // Operators
  1853. /**
  1854. * Adds in place the passed Color4 values to the current Color4 object
  1855. * @param right defines the second operand
  1856. * @returns the current updated Color4 object
  1857. */
  1858. Color4.prototype.addInPlace = function (right) {
  1859. this.r += right.r;
  1860. this.g += right.g;
  1861. this.b += right.b;
  1862. this.a += right.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1867. * @returns the new array
  1868. */
  1869. Color4.prototype.asArray = function () {
  1870. var result = new Array();
  1871. this.toArray(result, 0);
  1872. return result;
  1873. };
  1874. /**
  1875. * Stores from the starting index in the passed array the Color4 successive values
  1876. * @param array defines the array where to store the r,g,b components
  1877. * @param index defines an optional index in the target array to define where to start storing values
  1878. * @returns the current Color4 object
  1879. */
  1880. Color4.prototype.toArray = function (array, index) {
  1881. if (index === undefined) {
  1882. index = 0;
  1883. }
  1884. array[index] = this.r;
  1885. array[index + 1] = this.g;
  1886. array[index + 2] = this.b;
  1887. array[index + 3] = this.a;
  1888. return this;
  1889. };
  1890. /**
  1891. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1892. * @param right defines the second operand
  1893. * @returns a new Color4 object
  1894. */
  1895. Color4.prototype.add = function (right) {
  1896. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1897. };
  1898. /**
  1899. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1900. * @param right defines the second operand
  1901. * @returns a new Color4 object
  1902. */
  1903. Color4.prototype.subtract = function (right) {
  1904. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1905. };
  1906. /**
  1907. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1908. * @param right defines the second operand
  1909. * @param result defines the Color4 object where to store the result
  1910. * @returns the current Color4 object
  1911. */
  1912. Color4.prototype.subtractToRef = function (right, result) {
  1913. result.r = this.r - right.r;
  1914. result.g = this.g - right.g;
  1915. result.b = this.b - right.b;
  1916. result.a = this.a - right.a;
  1917. return this;
  1918. };
  1919. /**
  1920. * Creates a new Color4 with the current Color4 values multiplied by scale
  1921. * @param scale defines the scaling factor to apply
  1922. * @returns a new Color4 object
  1923. */
  1924. Color4.prototype.scale = function (scale) {
  1925. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1926. };
  1927. /**
  1928. * Multiplies the current Color4 values by scale and stores the result in "result"
  1929. * @param scale defines the scaling factor to apply
  1930. * @param result defines the Color4 object where to store the result
  1931. * @returns the current unmodified Color4
  1932. */
  1933. Color4.prototype.scaleToRef = function (scale, result) {
  1934. result.r = this.r * scale;
  1935. result.g = this.g * scale;
  1936. result.b = this.b * scale;
  1937. result.a = this.a * scale;
  1938. return this;
  1939. };
  1940. /**
  1941. * Scale the current Color4 values by a factor and add the result to a given Color4
  1942. * @param scale defines the scale factor
  1943. * @param result defines the Color4 object where to store the result
  1944. * @returns the unmodified current Color4
  1945. */
  1946. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1947. result.r += this.r * scale;
  1948. result.g += this.g * scale;
  1949. result.b += this.b * scale;
  1950. result.a += this.a * scale;
  1951. return this;
  1952. };
  1953. /**
  1954. * Clamps the rgb values by the min and max values and stores the result into "result"
  1955. * @param min defines minimum clamping value (default is 0)
  1956. * @param max defines maximum clamping value (default is 1)
  1957. * @param result defines color to store the result into.
  1958. * @returns the cuurent Color4
  1959. */
  1960. Color4.prototype.clampToRef = function (min, max, result) {
  1961. if (min === void 0) { min = 0; }
  1962. if (max === void 0) { max = 1; }
  1963. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1964. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1965. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1966. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1967. return this;
  1968. };
  1969. /**
  1970. * Multipy an Color4 value by another and return a new Color4 object
  1971. * @param color defines the Color4 value to multiply by
  1972. * @returns a new Color4 object
  1973. */
  1974. Color4.prototype.multiply = function (color) {
  1975. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1976. };
  1977. /**
  1978. * Multipy a Color4 value by another and push the result in a reference value
  1979. * @param color defines the Color4 value to multiply by
  1980. * @param result defines the Color4 to fill the result in
  1981. * @returns the result Color4
  1982. */
  1983. Color4.prototype.multiplyToRef = function (color, result) {
  1984. result.r = this.r * color.r;
  1985. result.g = this.g * color.g;
  1986. result.b = this.b * color.b;
  1987. result.a = this.a * color.a;
  1988. return result;
  1989. };
  1990. /**
  1991. * Creates a string with the Color4 current values
  1992. * @returns the string representation of the Color4 object
  1993. */
  1994. Color4.prototype.toString = function () {
  1995. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1996. };
  1997. /**
  1998. * Returns the string "Color4"
  1999. * @returns "Color4"
  2000. */
  2001. Color4.prototype.getClassName = function () {
  2002. return "Color4";
  2003. };
  2004. /**
  2005. * Compute the Color4 hash code
  2006. * @returns an unique number that can be used to hash Color4 objects
  2007. */
  2008. Color4.prototype.getHashCode = function () {
  2009. var hash = this.r || 0;
  2010. hash = (hash * 397) ^ (this.g || 0);
  2011. hash = (hash * 397) ^ (this.b || 0);
  2012. hash = (hash * 397) ^ (this.a || 0);
  2013. return hash;
  2014. };
  2015. /**
  2016. * Creates a new Color4 copied from the current one
  2017. * @returns a new Color4 object
  2018. */
  2019. Color4.prototype.clone = function () {
  2020. return new Color4(this.r, this.g, this.b, this.a);
  2021. };
  2022. /**
  2023. * Copies the passed Color4 values into the current one
  2024. * @param source defines the source Color4 object
  2025. * @returns the current updated Color4 object
  2026. */
  2027. Color4.prototype.copyFrom = function (source) {
  2028. this.r = source.r;
  2029. this.g = source.g;
  2030. this.b = source.b;
  2031. this.a = source.a;
  2032. return this;
  2033. };
  2034. /**
  2035. * Copies the passed float values into the current one
  2036. * @param r defines the red component to read from
  2037. * @param g defines the green component to read from
  2038. * @param b defines the blue component to read from
  2039. * @param a defines the alpha component to read from
  2040. * @returns the current updated Color4 object
  2041. */
  2042. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2043. this.r = r;
  2044. this.g = g;
  2045. this.b = b;
  2046. this.a = a;
  2047. return this;
  2048. };
  2049. /**
  2050. * Copies the passed float values into the current one
  2051. * @param r defines the red component to read from
  2052. * @param g defines the green component to read from
  2053. * @param b defines the blue component to read from
  2054. * @param a defines the alpha component to read from
  2055. * @returns the current updated Color4 object
  2056. */
  2057. Color4.prototype.set = function (r, g, b, a) {
  2058. return this.copyFromFloats(r, g, b, a);
  2059. };
  2060. /**
  2061. * Compute the Color4 hexadecimal code as a string
  2062. * @returns a string containing the hexadecimal representation of the Color4 object
  2063. */
  2064. Color4.prototype.toHexString = function () {
  2065. var intR = (this.r * 255) | 0;
  2066. var intG = (this.g * 255) | 0;
  2067. var intB = (this.b * 255) | 0;
  2068. var intA = (this.a * 255) | 0;
  2069. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2070. };
  2071. /**
  2072. * Computes a new Color4 converted from the current one to linear space
  2073. * @returns a new Color4 object
  2074. */
  2075. Color4.prototype.toLinearSpace = function () {
  2076. var convertedColor = new Color4();
  2077. this.toLinearSpaceToRef(convertedColor);
  2078. return convertedColor;
  2079. };
  2080. /**
  2081. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2082. * @param convertedColor defines the Color4 object where to store the linear space version
  2083. * @returns the unmodified Color4
  2084. */
  2085. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2086. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2087. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2088. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2089. convertedColor.a = this.a;
  2090. return this;
  2091. };
  2092. /**
  2093. * Computes a new Color4 converted from the current one to gamma space
  2094. * @returns a new Color4 object
  2095. */
  2096. Color4.prototype.toGammaSpace = function () {
  2097. var convertedColor = new Color4();
  2098. this.toGammaSpaceToRef(convertedColor);
  2099. return convertedColor;
  2100. };
  2101. /**
  2102. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2103. * @param convertedColor defines the Color4 object where to store the gamma space version
  2104. * @returns the unmodified Color4
  2105. */
  2106. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2107. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2108. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2109. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2110. convertedColor.a = this.a;
  2111. return this;
  2112. };
  2113. // Statics
  2114. /**
  2115. * Creates a new Color4 from the string containing valid hexadecimal values
  2116. * @param hex defines a string containing valid hexadecimal values
  2117. * @returns a new Color4 object
  2118. */
  2119. Color4.FromHexString = function (hex) {
  2120. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2121. return new Color4(0.0, 0.0, 0.0, 0.0);
  2122. }
  2123. var r = parseInt(hex.substring(1, 3), 16);
  2124. var g = parseInt(hex.substring(3, 5), 16);
  2125. var b = parseInt(hex.substring(5, 7), 16);
  2126. var a = parseInt(hex.substring(7, 9), 16);
  2127. return Color4.FromInts(r, g, b, a);
  2128. };
  2129. /**
  2130. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2131. * @param left defines the start value
  2132. * @param right defines the end value
  2133. * @param amount defines the gradient factor
  2134. * @returns a new Color4 object
  2135. */
  2136. Color4.Lerp = function (left, right, amount) {
  2137. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2138. Color4.LerpToRef(left, right, amount, result);
  2139. return result;
  2140. };
  2141. /**
  2142. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2143. * @param left defines the start value
  2144. * @param right defines the end value
  2145. * @param amount defines the gradient factor
  2146. * @param result defines the Color4 object where to store data
  2147. */
  2148. Color4.LerpToRef = function (left, right, amount, result) {
  2149. result.r = left.r + (right.r - left.r) * amount;
  2150. result.g = left.g + (right.g - left.g) * amount;
  2151. result.b = left.b + (right.b - left.b) * amount;
  2152. result.a = left.a + (right.a - left.a) * amount;
  2153. };
  2154. /**
  2155. * Creates a new Color4 from the starting index element of the passed array
  2156. * @param array defines the source array to read from
  2157. * @param offset defines the offset in the source array
  2158. * @returns a new Color4 object
  2159. */
  2160. Color4.FromArray = function (array, offset) {
  2161. if (offset === void 0) { offset = 0; }
  2162. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2163. };
  2164. /**
  2165. * Creates a new Color3 from integer values (< 256)
  2166. * @param r defines the red component to read from (value between 0 and 255)
  2167. * @param g defines the green component to read from (value between 0 and 255)
  2168. * @param b defines the blue component to read from (value between 0 and 255)
  2169. * @param a defines the alpha component to read from (value between 0 and 255)
  2170. * @returns a new Color3 object
  2171. */
  2172. Color4.FromInts = function (r, g, b, a) {
  2173. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2174. };
  2175. /**
  2176. * Check the content of a given array and convert it to an array containing RGBA data
  2177. * If the original array was already containing count * 4 values then it is returned directly
  2178. * @param colors defines the array to check
  2179. * @param count defines the number of RGBA data to expect
  2180. * @returns an array containing count * 4 values (RGBA)
  2181. */
  2182. Color4.CheckColors4 = function (colors, count) {
  2183. // Check if color3 was used
  2184. if (colors.length === count * 3) {
  2185. var colors4 = [];
  2186. for (var index = 0; index < colors.length; index += 3) {
  2187. var newIndex = (index / 3) * 4;
  2188. colors4[newIndex] = colors[index];
  2189. colors4[newIndex + 1] = colors[index + 1];
  2190. colors4[newIndex + 2] = colors[index + 2];
  2191. colors4[newIndex + 3] = 1.0;
  2192. }
  2193. return colors4;
  2194. }
  2195. return colors;
  2196. };
  2197. return Color4;
  2198. }());
  2199. BABYLON.Color4 = Color4;
  2200. var Vector2 = /** @class */ (function () {
  2201. /**
  2202. * Creates a new Vector2 from the passed x and y coordinates.
  2203. */
  2204. function Vector2(x, y) {
  2205. this.x = x;
  2206. this.y = y;
  2207. }
  2208. /**
  2209. * Returns a string with the Vector2 coordinates.
  2210. */
  2211. Vector2.prototype.toString = function () {
  2212. return "{X: " + this.x + " Y:" + this.y + "}";
  2213. };
  2214. /**
  2215. * Returns the string "Vector2"
  2216. */
  2217. Vector2.prototype.getClassName = function () {
  2218. return "Vector2";
  2219. };
  2220. /**
  2221. * Returns the Vector2 hash code as a number.
  2222. */
  2223. Vector2.prototype.getHashCode = function () {
  2224. var hash = this.x || 0;
  2225. hash = (hash * 397) ^ (this.y || 0);
  2226. return hash;
  2227. };
  2228. // Operators
  2229. /**
  2230. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2231. * Returns the Vector2.
  2232. */
  2233. Vector2.prototype.toArray = function (array, index) {
  2234. if (index === void 0) { index = 0; }
  2235. array[index] = this.x;
  2236. array[index + 1] = this.y;
  2237. return this;
  2238. };
  2239. /**
  2240. * Returns a new array with 2 elements : the Vector2 coordinates.
  2241. */
  2242. Vector2.prototype.asArray = function () {
  2243. var result = new Array();
  2244. this.toArray(result, 0);
  2245. return result;
  2246. };
  2247. /**
  2248. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2249. * Returns the updated Vector2.
  2250. */
  2251. Vector2.prototype.copyFrom = function (source) {
  2252. this.x = source.x;
  2253. this.y = source.y;
  2254. return this;
  2255. };
  2256. /**
  2257. * Sets the Vector2 coordinates with the passed floats.
  2258. * Returns the updated Vector2.
  2259. */
  2260. Vector2.prototype.copyFromFloats = function (x, y) {
  2261. this.x = x;
  2262. this.y = y;
  2263. return this;
  2264. };
  2265. /**
  2266. * Sets the Vector2 coordinates with the passed floats.
  2267. * Returns the updated Vector2.
  2268. */
  2269. Vector2.prototype.set = function (x, y) {
  2270. return this.copyFromFloats(x, y);
  2271. };
  2272. /**
  2273. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2274. */
  2275. Vector2.prototype.add = function (otherVector) {
  2276. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2277. };
  2278. /**
  2279. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2280. * Returns the Vector2.
  2281. */
  2282. Vector2.prototype.addToRef = function (otherVector, result) {
  2283. result.x = this.x + otherVector.x;
  2284. result.y = this.y + otherVector.y;
  2285. return this;
  2286. };
  2287. /**
  2288. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2289. * Returns the updated Vector2.
  2290. */
  2291. Vector2.prototype.addInPlace = function (otherVector) {
  2292. this.x += otherVector.x;
  2293. this.y += otherVector.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2298. */
  2299. Vector2.prototype.addVector3 = function (otherVector) {
  2300. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2301. };
  2302. /**
  2303. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2304. */
  2305. Vector2.prototype.subtract = function (otherVector) {
  2306. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2307. };
  2308. /**
  2309. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2310. * Returns the Vector2.
  2311. */
  2312. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2313. result.x = this.x - otherVector.x;
  2314. result.y = this.y - otherVector.y;
  2315. return this;
  2316. };
  2317. /**
  2318. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2319. * Returns the updated Vector2.
  2320. */
  2321. Vector2.prototype.subtractInPlace = function (otherVector) {
  2322. this.x -= otherVector.x;
  2323. this.y -= otherVector.y;
  2324. return this;
  2325. };
  2326. /**
  2327. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2328. * Returns the updated Vector2.
  2329. */
  2330. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2331. this.x *= otherVector.x;
  2332. this.y *= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2337. */
  2338. Vector2.prototype.multiply = function (otherVector) {
  2339. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2340. };
  2341. /**
  2342. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2343. * Returns the Vector2.
  2344. */
  2345. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2346. result.x = this.x * otherVector.x;
  2347. result.y = this.y * otherVector.y;
  2348. return this;
  2349. };
  2350. /**
  2351. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2352. */
  2353. Vector2.prototype.multiplyByFloats = function (x, y) {
  2354. return new Vector2(this.x * x, this.y * y);
  2355. };
  2356. /**
  2357. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2358. */
  2359. Vector2.prototype.divide = function (otherVector) {
  2360. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2361. };
  2362. /**
  2363. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2364. * Returns the Vector2.
  2365. */
  2366. Vector2.prototype.divideToRef = function (otherVector, result) {
  2367. result.x = this.x / otherVector.x;
  2368. result.y = this.y / otherVector.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Divides the current Vector3 coordinates by the passed ones.
  2373. * Returns the updated Vector3.
  2374. */
  2375. Vector2.prototype.divideInPlace = function (otherVector) {
  2376. return this.divideToRef(otherVector, this);
  2377. };
  2378. /**
  2379. * Returns a new Vector2 with current Vector2 negated coordinates.
  2380. */
  2381. Vector2.prototype.negate = function () {
  2382. return new Vector2(-this.x, -this.y);
  2383. };
  2384. /**
  2385. * Multiply the Vector2 coordinates by scale.
  2386. * Returns the updated Vector2.
  2387. */
  2388. Vector2.prototype.scaleInPlace = function (scale) {
  2389. this.x *= scale;
  2390. this.y *= scale;
  2391. return this;
  2392. };
  2393. /**
  2394. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2395. */
  2396. Vector2.prototype.scale = function (scale) {
  2397. var result = new Vector2(0, 0);
  2398. this.scaleToRef(scale, result);
  2399. return result;
  2400. };
  2401. /**
  2402. * Scale the current Vector2 values by a factor to a given Vector2
  2403. * @param scale defines the scale factor
  2404. * @param result defines the Vector2 object where to store the result
  2405. * @returns the unmodified current Vector2
  2406. */
  2407. Vector2.prototype.scaleToRef = function (scale, result) {
  2408. result.x = this.x * scale;
  2409. result.y = this.y * scale;
  2410. return this;
  2411. };
  2412. /**
  2413. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2414. * @param scale defines the scale factor
  2415. * @param result defines the Vector2 object where to store the result
  2416. * @returns the unmodified current Vector2
  2417. */
  2418. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2419. result.x += this.x * scale;
  2420. result.y += this.y * scale;
  2421. return this;
  2422. };
  2423. /**
  2424. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2425. */
  2426. Vector2.prototype.equals = function (otherVector) {
  2427. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2428. };
  2429. /**
  2430. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2431. */
  2432. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2433. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2434. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2435. };
  2436. // Properties
  2437. /**
  2438. * Returns the vector length (float).
  2439. */
  2440. Vector2.prototype.length = function () {
  2441. return Math.sqrt(this.x * this.x + this.y * this.y);
  2442. };
  2443. /**
  2444. * Returns the vector squared length (float);
  2445. */
  2446. Vector2.prototype.lengthSquared = function () {
  2447. return (this.x * this.x + this.y * this.y);
  2448. };
  2449. // Methods
  2450. /**
  2451. * Normalize the vector.
  2452. * Returns the updated Vector2.
  2453. */
  2454. Vector2.prototype.normalize = function () {
  2455. var len = this.length();
  2456. if (len === 0)
  2457. return this;
  2458. var num = 1.0 / len;
  2459. this.x *= num;
  2460. this.y *= num;
  2461. return this;
  2462. };
  2463. /**
  2464. * Returns a new Vector2 copied from the Vector2.
  2465. */
  2466. Vector2.prototype.clone = function () {
  2467. return new Vector2(this.x, this.y);
  2468. };
  2469. // Statics
  2470. /**
  2471. * Returns a new Vector2(0, 0)
  2472. */
  2473. Vector2.Zero = function () {
  2474. return new Vector2(0, 0);
  2475. };
  2476. /**
  2477. * Returns a new Vector2(1, 1)
  2478. */
  2479. Vector2.One = function () {
  2480. return new Vector2(1, 1);
  2481. };
  2482. /**
  2483. * Returns a new Vector2 set from the passed index element of the passed array.
  2484. */
  2485. Vector2.FromArray = function (array, offset) {
  2486. if (offset === void 0) { offset = 0; }
  2487. return new Vector2(array[offset], array[offset + 1]);
  2488. };
  2489. /**
  2490. * Sets "result" from the passed index element of the passed array.
  2491. */
  2492. Vector2.FromArrayToRef = function (array, offset, result) {
  2493. result.x = array[offset];
  2494. result.y = array[offset + 1];
  2495. };
  2496. /**
  2497. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2498. */
  2499. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2500. var squared = amount * amount;
  2501. var cubed = amount * squared;
  2502. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2503. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2504. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2505. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2506. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2507. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2508. return new Vector2(x, y);
  2509. };
  2510. /**
  2511. * 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".
  2512. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2513. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2514. */
  2515. Vector2.Clamp = function (value, min, max) {
  2516. var x = value.x;
  2517. x = (x > max.x) ? max.x : x;
  2518. x = (x < min.x) ? min.x : x;
  2519. var y = value.y;
  2520. y = (y > max.y) ? max.y : y;
  2521. y = (y < min.y) ? min.y : y;
  2522. return new Vector2(x, y);
  2523. };
  2524. /**
  2525. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2526. */
  2527. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2528. var squared = amount * amount;
  2529. var cubed = amount * squared;
  2530. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2531. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2532. var part3 = (cubed - (2.0 * squared)) + amount;
  2533. var part4 = cubed - squared;
  2534. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2535. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2536. return new Vector2(x, y);
  2537. };
  2538. /**
  2539. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2540. */
  2541. Vector2.Lerp = function (start, end, amount) {
  2542. var x = start.x + ((end.x - start.x) * amount);
  2543. var y = start.y + ((end.y - start.y) * amount);
  2544. return new Vector2(x, y);
  2545. };
  2546. /**
  2547. * Returns the dot product (float) of the vector "left" and the vector "right".
  2548. */
  2549. Vector2.Dot = function (left, right) {
  2550. return left.x * right.x + left.y * right.y;
  2551. };
  2552. /**
  2553. * Returns a new Vector2 equal to the normalized passed vector.
  2554. */
  2555. Vector2.Normalize = function (vector) {
  2556. var newVector = vector.clone();
  2557. newVector.normalize();
  2558. return newVector;
  2559. };
  2560. /**
  2561. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2562. */
  2563. Vector2.Minimize = function (left, right) {
  2564. var x = (left.x < right.x) ? left.x : right.x;
  2565. var y = (left.y < right.y) ? left.y : right.y;
  2566. return new Vector2(x, y);
  2567. };
  2568. /**
  2569. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2570. */
  2571. Vector2.Maximize = function (left, right) {
  2572. var x = (left.x > right.x) ? left.x : right.x;
  2573. var y = (left.y > right.y) ? left.y : right.y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2578. */
  2579. Vector2.Transform = function (vector, transformation) {
  2580. var r = Vector2.Zero();
  2581. Vector2.TransformToRef(vector, transformation, r);
  2582. return r;
  2583. };
  2584. /**
  2585. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2586. */
  2587. Vector2.TransformToRef = function (vector, transformation, result) {
  2588. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2589. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2590. result.x = x;
  2591. result.y = y;
  2592. };
  2593. /**
  2594. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2595. */
  2596. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2597. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2598. var sign = a < 0 ? -1 : 1;
  2599. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2600. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2601. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2602. };
  2603. /**
  2604. * Returns the distance (float) between the vectors "value1" and "value2".
  2605. */
  2606. Vector2.Distance = function (value1, value2) {
  2607. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2608. };
  2609. /**
  2610. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2611. */
  2612. Vector2.DistanceSquared = function (value1, value2) {
  2613. var x = value1.x - value2.x;
  2614. var y = value1.y - value2.y;
  2615. return (x * x) + (y * y);
  2616. };
  2617. /**
  2618. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2619. */
  2620. Vector2.Center = function (value1, value2) {
  2621. var center = value1.add(value2);
  2622. center.scaleInPlace(0.5);
  2623. return center;
  2624. };
  2625. /**
  2626. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2627. */
  2628. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2629. var l2 = Vector2.DistanceSquared(segA, segB);
  2630. if (l2 === 0.0) {
  2631. return Vector2.Distance(p, segA);
  2632. }
  2633. var v = segB.subtract(segA);
  2634. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2635. var proj = segA.add(v.multiplyByFloats(t, t));
  2636. return Vector2.Distance(p, proj);
  2637. };
  2638. return Vector2;
  2639. }());
  2640. BABYLON.Vector2 = Vector2;
  2641. /**
  2642. * Classed used to store (x,y,z) vector representation
  2643. * A Vector3 is the main object used in 3D geometry
  2644. * It can represent etiher the coordinates of a point the space, either a direction
  2645. * Reminder: Babylon.js uses a left handed forward facing system
  2646. */
  2647. var Vector3 = /** @class */ (function () {
  2648. /**
  2649. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2650. * @param x defines the first coordinates (on X axis)
  2651. * @param y defines the second coordinates (on Y axis)
  2652. * @param z defines the third coordinates (on Z axis)
  2653. */
  2654. function Vector3(
  2655. /**
  2656. * Defines the first coordinates (on X axis)
  2657. */
  2658. x,
  2659. /**
  2660. * Defines the second coordinates (on Y axis)
  2661. */
  2662. y,
  2663. /**
  2664. * Defines the third coordinates (on Z axis)
  2665. */
  2666. z) {
  2667. this.x = x;
  2668. this.y = y;
  2669. this.z = z;
  2670. }
  2671. /**
  2672. * Creates a string representation of the Vector3
  2673. * @returns a string with the Vector3 coordinates.
  2674. */
  2675. Vector3.prototype.toString = function () {
  2676. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2677. };
  2678. /**
  2679. * Gets the class name
  2680. * @returns the string "Vector3"
  2681. */
  2682. Vector3.prototype.getClassName = function () {
  2683. return "Vector3";
  2684. };
  2685. /**
  2686. * Creates the Vector3 hash code
  2687. * @returns a number which tends to be unique between Vector3 instances
  2688. */
  2689. Vector3.prototype.getHashCode = function () {
  2690. var hash = this.x || 0;
  2691. hash = (hash * 397) ^ (this.y || 0);
  2692. hash = (hash * 397) ^ (this.z || 0);
  2693. return hash;
  2694. };
  2695. // Operators
  2696. /**
  2697. * Creates an array containing three elements : the coordinates of the Vector3
  2698. * @returns a new array of numbers
  2699. */
  2700. Vector3.prototype.asArray = function () {
  2701. var result = [];
  2702. this.toArray(result, 0);
  2703. return result;
  2704. };
  2705. /**
  2706. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2707. * @param array defines the destination array
  2708. * @param index defines the offset in the destination array
  2709. * @returns the current Vector3
  2710. */
  2711. Vector3.prototype.toArray = function (array, index) {
  2712. if (index === void 0) { index = 0; }
  2713. array[index] = this.x;
  2714. array[index + 1] = this.y;
  2715. array[index + 2] = this.z;
  2716. return this;
  2717. };
  2718. /**
  2719. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2720. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2721. */
  2722. Vector3.prototype.toQuaternion = function () {
  2723. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2724. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2725. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2726. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2727. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2728. var cosy = Math.cos(this.y * 0.5);
  2729. var siny = Math.sin(this.y * 0.5);
  2730. result.x = coszMinusx * siny;
  2731. result.y = -sinzMinusx * siny;
  2732. result.z = sinxPlusz * cosy;
  2733. result.w = cosxPlusz * cosy;
  2734. return result;
  2735. };
  2736. /**
  2737. * Adds the passed vector to the current Vector3
  2738. * @param otherVector defines the second operand
  2739. * @returns the current updated Vector3
  2740. */
  2741. Vector3.prototype.addInPlace = function (otherVector) {
  2742. this.x += otherVector.x;
  2743. this.y += otherVector.y;
  2744. this.z += otherVector.z;
  2745. return this;
  2746. };
  2747. /**
  2748. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2749. * @param otherVector defines the second operand
  2750. * @returns the resulting Vector3
  2751. */
  2752. Vector3.prototype.add = function (otherVector) {
  2753. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2754. };
  2755. /**
  2756. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2757. * @param otherVector defines the second operand
  2758. * @param result defines the Vector3 object where to store the result
  2759. * @returns the current Vector3
  2760. */
  2761. Vector3.prototype.addToRef = function (otherVector, result) {
  2762. result.x = this.x + otherVector.x;
  2763. result.y = this.y + otherVector.y;
  2764. result.z = this.z + otherVector.z;
  2765. return this;
  2766. };
  2767. /**
  2768. * Subtract the passed vector from the current Vector3
  2769. * @param otherVector defines the second operand
  2770. * @returns the current updated Vector3
  2771. */
  2772. Vector3.prototype.subtractInPlace = function (otherVector) {
  2773. this.x -= otherVector.x;
  2774. this.y -= otherVector.y;
  2775. this.z -= otherVector.z;
  2776. return this;
  2777. };
  2778. /**
  2779. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2780. * @param otherVector defines the second operand
  2781. * @returns the resulting Vector3
  2782. */
  2783. Vector3.prototype.subtract = function (otherVector) {
  2784. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2785. };
  2786. /**
  2787. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2788. * @param otherVector defines the second operand
  2789. * @param result defines the Vector3 object where to store the result
  2790. * @returns the current Vector3
  2791. */
  2792. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2793. result.x = this.x - otherVector.x;
  2794. result.y = this.y - otherVector.y;
  2795. result.z = this.z - otherVector.z;
  2796. return this;
  2797. };
  2798. /**
  2799. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2800. * @param x defines the x coordinate of the operand
  2801. * @param y defines the y coordinate of the operand
  2802. * @param z defines the z coordinate of the operand
  2803. * @returns the resulting Vector3
  2804. */
  2805. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2806. return new Vector3(this.x - x, this.y - y, this.z - z);
  2807. };
  2808. /**
  2809. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2810. * @param x defines the x coordinate of the operand
  2811. * @param y defines the y coordinate of the operand
  2812. * @param z defines the z coordinate of the operand
  2813. * @param result defines the Vector3 object where to store the result
  2814. * @returns the current Vector3
  2815. */
  2816. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2817. result.x = this.x - x;
  2818. result.y = this.y - y;
  2819. result.z = this.z - z;
  2820. return this;
  2821. };
  2822. /**
  2823. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2824. * @returns a new Vector3
  2825. */
  2826. Vector3.prototype.negate = function () {
  2827. return new Vector3(-this.x, -this.y, -this.z);
  2828. };
  2829. /**
  2830. * Multiplies the Vector3 coordinates by the float "scale"
  2831. * @param scale defines the multiplier factor
  2832. * @returns the current updated Vector3
  2833. */
  2834. Vector3.prototype.scaleInPlace = function (scale) {
  2835. this.x *= scale;
  2836. this.y *= scale;
  2837. this.z *= scale;
  2838. return this;
  2839. };
  2840. /**
  2841. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2842. * @param scale defines the multiplier factor
  2843. * @returns a new Vector3
  2844. */
  2845. Vector3.prototype.scale = function (scale) {
  2846. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2847. };
  2848. /**
  2849. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2850. * @param scale defines the multiplier factor
  2851. * @param result defines the Vector3 object where to store the result
  2852. * @returns the current Vector3
  2853. */
  2854. Vector3.prototype.scaleToRef = function (scale, result) {
  2855. result.x = this.x * scale;
  2856. result.y = this.y * scale;
  2857. result.z = this.z * scale;
  2858. return this;
  2859. };
  2860. /**
  2861. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2862. * @param scale defines the scale factor
  2863. * @param result defines the Vector3 object where to store the result
  2864. * @returns the unmodified current Vector3
  2865. */
  2866. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2867. result.x += this.x * scale;
  2868. result.y += this.y * scale;
  2869. result.z += this.z * scale;
  2870. return this;
  2871. };
  2872. /**
  2873. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2874. * @param otherVector defines the second operand
  2875. * @returns true if both vectors are equals
  2876. */
  2877. Vector3.prototype.equals = function (otherVector) {
  2878. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2879. };
  2880. /**
  2881. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2882. * @param otherVector defines the second operand
  2883. * @param epsilon defines the minimal distance to define values as equals
  2884. * @returns true if both vectors are distant less than epsilon
  2885. */
  2886. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2887. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2888. 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);
  2889. };
  2890. /**
  2891. * Returns true if the current Vector3 coordinates equals the passed floats
  2892. * @param x defines the x coordinate of the operand
  2893. * @param y defines the y coordinate of the operand
  2894. * @param z defines the z coordinate of the operand
  2895. * @returns true if both vectors are equals
  2896. */
  2897. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2898. return this.x === x && this.y === y && this.z === z;
  2899. };
  2900. /**
  2901. * Multiplies the current Vector3 coordinates by the passed ones
  2902. * @param otherVector defines the second operand
  2903. * @returns the current updated Vector3
  2904. */
  2905. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2906. this.x *= otherVector.x;
  2907. this.y *= otherVector.y;
  2908. this.z *= otherVector.z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2913. * @param otherVector defines the second operand
  2914. * @returns the new Vector3
  2915. */
  2916. Vector3.prototype.multiply = function (otherVector) {
  2917. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2918. };
  2919. /**
  2920. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2921. * @param otherVector defines the second operand
  2922. * @param result defines the Vector3 object where to store the result
  2923. * @returns the current Vector3
  2924. */
  2925. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2926. result.x = this.x * otherVector.x;
  2927. result.y = this.y * otherVector.y;
  2928. result.z = this.z * otherVector.z;
  2929. return this;
  2930. };
  2931. /**
  2932. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2933. * @param x defines the x coordinate of the operand
  2934. * @param y defines the y coordinate of the operand
  2935. * @param z defines the z coordinate of the operand
  2936. * @returns the new Vector3
  2937. */
  2938. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2939. return new Vector3(this.x * x, this.y * y, this.z * z);
  2940. };
  2941. /**
  2942. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2943. * @param otherVector defines the second operand
  2944. * @returns the new Vector3
  2945. */
  2946. Vector3.prototype.divide = function (otherVector) {
  2947. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2948. };
  2949. /**
  2950. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2951. * @param otherVector defines the second operand
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the current Vector3
  2954. */
  2955. Vector3.prototype.divideToRef = function (otherVector, result) {
  2956. result.x = this.x / otherVector.x;
  2957. result.y = this.y / otherVector.y;
  2958. result.z = this.z / otherVector.z;
  2959. return this;
  2960. };
  2961. /**
  2962. * Divides the current Vector3 coordinates by the passed ones.
  2963. * @param otherVector defines the second operand
  2964. * @returns the current updated Vector3
  2965. */
  2966. Vector3.prototype.divideInPlace = function (otherVector) {
  2967. return this.divideToRef(otherVector, this);
  2968. };
  2969. /**
  2970. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2971. * @param other defines the second operand
  2972. * @returns the current updated Vector3
  2973. */
  2974. Vector3.prototype.minimizeInPlace = function (other) {
  2975. if (other.x < this.x)
  2976. this.x = other.x;
  2977. if (other.y < this.y)
  2978. this.y = other.y;
  2979. if (other.z < this.z)
  2980. this.z = other.z;
  2981. return this;
  2982. };
  2983. /**
  2984. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2985. * @param other defines the second operand
  2986. * @returns the current updated Vector3
  2987. */
  2988. Vector3.prototype.maximizeInPlace = function (other) {
  2989. if (other.x > this.x)
  2990. this.x = other.x;
  2991. if (other.y > this.y)
  2992. this.y = other.y;
  2993. if (other.z > this.z)
  2994. this.z = other.z;
  2995. return this;
  2996. };
  2997. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2998. /**
  2999. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3000. */
  3001. get: function () {
  3002. var absX = Math.abs(this.x);
  3003. var absY = Math.abs(this.y);
  3004. if (absX !== absY) {
  3005. return true;
  3006. }
  3007. var absZ = Math.abs(this.z);
  3008. if (absX !== absZ) {
  3009. return true;
  3010. }
  3011. if (absY !== absZ) {
  3012. return true;
  3013. }
  3014. return false;
  3015. },
  3016. enumerable: true,
  3017. configurable: true
  3018. });
  3019. // Properties
  3020. /**
  3021. * Gets the length of the Vector3
  3022. * @returns the length of the Vecto3
  3023. */
  3024. Vector3.prototype.length = function () {
  3025. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3026. };
  3027. /**
  3028. * Gets the squared length of the Vector3
  3029. * @returns squared length of the Vector3
  3030. */
  3031. Vector3.prototype.lengthSquared = function () {
  3032. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3033. };
  3034. /**
  3035. * Normalize the current Vector3.
  3036. * Please note that this is an in place operation.
  3037. * @returns the current updated Vector3
  3038. */
  3039. Vector3.prototype.normalize = function () {
  3040. var len = this.length();
  3041. if (len === 0 || len === 1.0)
  3042. return this;
  3043. var num = 1.0 / len;
  3044. this.x *= num;
  3045. this.y *= num;
  3046. this.z *= num;
  3047. return this;
  3048. };
  3049. /**
  3050. * Normalize the current Vector3 to a new vector
  3051. * @returns the new Vector3
  3052. */
  3053. Vector3.prototype.normalizeToNew = function () {
  3054. var normalized = new Vector3(0, 0, 0);
  3055. this.normalizeToRef(normalized);
  3056. return normalized;
  3057. };
  3058. /**
  3059. * Normalize the current Vector3 to the reference
  3060. * @param reference define the Vector3 to update
  3061. * @returns the updated Vector3
  3062. */
  3063. Vector3.prototype.normalizeToRef = function (reference) {
  3064. var len = this.length();
  3065. if (len === 0 || len === 1.0) {
  3066. reference.set(this.x, this.y, this.z);
  3067. return reference;
  3068. }
  3069. var scale = 1.0 / len;
  3070. this.scaleToRef(scale, reference);
  3071. return reference;
  3072. };
  3073. /**
  3074. * Creates a new Vector3 copied from the current Vector3
  3075. * @returns the new Vector3
  3076. */
  3077. Vector3.prototype.clone = function () {
  3078. return new Vector3(this.x, this.y, this.z);
  3079. };
  3080. /**
  3081. * Copies the passed vector coordinates to the current Vector3 ones
  3082. * @param source defines the source Vector3
  3083. * @returns the current updated Vector3
  3084. */
  3085. Vector3.prototype.copyFrom = function (source) {
  3086. this.x = source.x;
  3087. this.y = source.y;
  3088. this.z = source.z;
  3089. return this;
  3090. };
  3091. /**
  3092. * Copies the passed floats to the current Vector3 coordinates
  3093. * @param x defines the x coordinate of the operand
  3094. * @param y defines the y coordinate of the operand
  3095. * @param z defines the z coordinate of the operand
  3096. * @returns the current updated Vector3
  3097. */
  3098. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3099. this.x = x;
  3100. this.y = y;
  3101. this.z = z;
  3102. return this;
  3103. };
  3104. /**
  3105. * Copies the passed floats to the current Vector3 coordinates
  3106. * @param x defines the x coordinate of the operand
  3107. * @param y defines the y coordinate of the operand
  3108. * @param z defines the z coordinate of the operand
  3109. * @returns the current updated Vector3
  3110. */
  3111. Vector3.prototype.set = function (x, y, z) {
  3112. return this.copyFromFloats(x, y, z);
  3113. };
  3114. // Statics
  3115. /**
  3116. * Get the clip factor between two vectors
  3117. * @param vector0 defines the first operand
  3118. * @param vector1 defines the second operand
  3119. * @param axis defines the axis to use
  3120. * @param size defines the size along the axis
  3121. * @returns the clip factor
  3122. */
  3123. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3124. var d0 = Vector3.Dot(vector0, axis) - size;
  3125. var d1 = Vector3.Dot(vector1, axis) - size;
  3126. var s = d0 / (d0 - d1);
  3127. return s;
  3128. };
  3129. /**
  3130. * Get angle between two vectors
  3131. * @param vector0 angle between vector0 and vector1
  3132. * @param vector1 angle between vector0 and vector1
  3133. * @param normal direction of the normal
  3134. * @return the angle between vector0 and vector1
  3135. */
  3136. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3137. var v0 = vector0.clone().normalize();
  3138. var v1 = vector1.clone().normalize();
  3139. var dot = Vector3.Dot(v0, v1);
  3140. var n = Vector3.Cross(v0, v1);
  3141. if (Vector3.Dot(n, normal) > 0) {
  3142. return Math.acos(dot);
  3143. }
  3144. return -Math.acos(dot);
  3145. };
  3146. /**
  3147. * Returns a new Vector3 set from the index "offset" of the passed array
  3148. * @param array defines the source array
  3149. * @param offset defines the offset in the source array
  3150. * @returns the new Vector3
  3151. */
  3152. Vector3.FromArray = function (array, offset) {
  3153. if (!offset) {
  3154. offset = 0;
  3155. }
  3156. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3157. };
  3158. /**
  3159. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3160. * This function is deprecated. Use FromArray instead
  3161. * @param array defines the source array
  3162. * @param offset defines the offset in the source array
  3163. * @returns the new Vector3
  3164. */
  3165. Vector3.FromFloatArray = function (array, offset) {
  3166. return Vector3.FromArray(array, offset);
  3167. };
  3168. /**
  3169. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3170. * @param array defines the source array
  3171. * @param offset defines the offset in the source array
  3172. * @param result defines the Vector3 where to store the result
  3173. */
  3174. Vector3.FromArrayToRef = function (array, offset, result) {
  3175. result.x = array[offset];
  3176. result.y = array[offset + 1];
  3177. result.z = array[offset + 2];
  3178. };
  3179. /**
  3180. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3181. * This function is deprecated. Use FromArrayToRef instead.
  3182. * @param array defines the source array
  3183. * @param offset defines the offset in the source array
  3184. * @param result defines the Vector3 where to store the result
  3185. */
  3186. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3187. return Vector3.FromArrayToRef(array, offset, result);
  3188. };
  3189. /**
  3190. * Sets the passed vector "result" with the passed floats.
  3191. * @param x defines the x coordinate of the source
  3192. * @param y defines the y coordinate of the source
  3193. * @param z defines the z coordinate of the source
  3194. * @param result defines the Vector3 where to store the result
  3195. */
  3196. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3197. result.x = x;
  3198. result.y = y;
  3199. result.z = z;
  3200. };
  3201. /**
  3202. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3203. * @returns a new empty Vector3
  3204. */
  3205. Vector3.Zero = function () {
  3206. return new Vector3(0.0, 0.0, 0.0);
  3207. };
  3208. /**
  3209. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3210. * @returns a new unit Vector3
  3211. */
  3212. Vector3.One = function () {
  3213. return new Vector3(1.0, 1.0, 1.0);
  3214. };
  3215. /**
  3216. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3217. * @returns a new up Vector3
  3218. */
  3219. Vector3.Up = function () {
  3220. return new Vector3(0.0, 1.0, 0.0);
  3221. };
  3222. /**
  3223. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3224. * @returns a new forward Vector3
  3225. */
  3226. Vector3.Forward = function () {
  3227. return new Vector3(0.0, 0.0, 1.0);
  3228. };
  3229. /**
  3230. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3231. * @returns a new right Vector3
  3232. */
  3233. Vector3.Right = function () {
  3234. return new Vector3(1.0, 0.0, 0.0);
  3235. };
  3236. /**
  3237. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3238. * @returns a new left Vector3
  3239. */
  3240. Vector3.Left = function () {
  3241. return new Vector3(-1.0, 0.0, 0.0);
  3242. };
  3243. /**
  3244. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3245. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3246. * @param vector defines the Vector3 to transform
  3247. * @param transformation defines the transformation matrix
  3248. * @returns the transformed Vector3
  3249. */
  3250. Vector3.TransformCoordinates = function (vector, transformation) {
  3251. var result = Vector3.Zero();
  3252. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3253. return result;
  3254. };
  3255. /**
  3256. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3257. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3258. * @param vector defines the Vector3 to transform
  3259. * @param transformation defines the transformation matrix
  3260. * @param result defines the Vector3 where to store the result
  3261. */
  3262. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3263. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3264. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3265. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3266. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3267. result.x = x / w;
  3268. result.y = y / w;
  3269. result.z = z / w;
  3270. };
  3271. /**
  3272. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3273. * This method computes tranformed coordinates only, not transformed direction vectors
  3274. * @param x define the x coordinate of the source vector
  3275. * @param y define the y coordinate of the source vector
  3276. * @param z define the z coordinate of the source vector
  3277. * @param transformation defines the transformation matrix
  3278. * @param result defines the Vector3 where to store the result
  3279. */
  3280. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3281. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3282. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3283. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3284. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3285. result.x = rx / rw;
  3286. result.y = ry / rw;
  3287. result.z = rz / rw;
  3288. };
  3289. /**
  3290. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3291. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3292. * @param vector defines the Vector3 to transform
  3293. * @param transformation defines the transformation matrix
  3294. * @returns the new Vector3
  3295. */
  3296. Vector3.TransformNormal = function (vector, transformation) {
  3297. var result = Vector3.Zero();
  3298. Vector3.TransformNormalToRef(vector, transformation, result);
  3299. return result;
  3300. };
  3301. /**
  3302. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3303. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3304. * @param vector defines the Vector3 to transform
  3305. * @param transformation defines the transformation matrix
  3306. * @param result defines the Vector3 where to store the result
  3307. */
  3308. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3309. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3310. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3311. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3312. result.x = x;
  3313. result.y = y;
  3314. result.z = z;
  3315. };
  3316. /**
  3317. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3318. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3319. * @param x define the x coordinate of the source vector
  3320. * @param y define the y coordinate of the source vector
  3321. * @param z define the z coordinate of the source vector
  3322. * @param transformation defines the transformation matrix
  3323. * @param result defines the Vector3 where to store the result
  3324. */
  3325. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3326. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3327. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3328. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3329. };
  3330. /**
  3331. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3332. * @param value1 defines the first control point
  3333. * @param value2 defines the second control point
  3334. * @param value3 defines the third control point
  3335. * @param value4 defines the fourth control point
  3336. * @param amount defines the amount on the spline to use
  3337. * @returns the new Vector3
  3338. */
  3339. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3340. var squared = amount * amount;
  3341. var cubed = amount * squared;
  3342. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3343. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3344. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3345. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3346. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3347. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3348. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3349. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3350. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3351. return new Vector3(x, y, z);
  3352. };
  3353. /**
  3354. * 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"
  3355. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3356. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3357. * @param value defines the current value
  3358. * @param min defines the lower range value
  3359. * @param max defines the upper range value
  3360. * @returns the new Vector3
  3361. */
  3362. Vector3.Clamp = function (value, min, max) {
  3363. var x = value.x;
  3364. x = (x > max.x) ? max.x : x;
  3365. x = (x < min.x) ? min.x : x;
  3366. var y = value.y;
  3367. y = (y > max.y) ? max.y : y;
  3368. y = (y < min.y) ? min.y : y;
  3369. var z = value.z;
  3370. z = (z > max.z) ? max.z : z;
  3371. z = (z < min.z) ? min.z : z;
  3372. return new Vector3(x, y, z);
  3373. };
  3374. /**
  3375. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3376. * @param value1 defines the first control point
  3377. * @param tangent1 defines the first tangent vector
  3378. * @param value2 defines the second control point
  3379. * @param tangent2 defines the second tangent vector
  3380. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3381. * @returns the new Vector3
  3382. */
  3383. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3384. var squared = amount * amount;
  3385. var cubed = amount * squared;
  3386. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3387. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3388. var part3 = (cubed - (2.0 * squared)) + amount;
  3389. var part4 = cubed - squared;
  3390. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3391. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3392. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3393. return new Vector3(x, y, z);
  3394. };
  3395. /**
  3396. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3397. * @param start defines the start value
  3398. * @param end defines the end value
  3399. * @param amount max defines amount between both (between 0 and 1)
  3400. * @returns the new Vector3
  3401. */
  3402. Vector3.Lerp = function (start, end, amount) {
  3403. var result = new Vector3(0, 0, 0);
  3404. Vector3.LerpToRef(start, end, amount, result);
  3405. return result;
  3406. };
  3407. /**
  3408. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3409. * @param start defines the start value
  3410. * @param end defines the end value
  3411. * @param amount max defines amount between both (between 0 and 1)
  3412. * @param result defines the Vector3 where to store the result
  3413. */
  3414. Vector3.LerpToRef = function (start, end, amount, result) {
  3415. result.x = start.x + ((end.x - start.x) * amount);
  3416. result.y = start.y + ((end.y - start.y) * amount);
  3417. result.z = start.z + ((end.z - start.z) * amount);
  3418. };
  3419. /**
  3420. * Returns the dot product (float) between the vectors "left" and "right"
  3421. * @param left defines the left operand
  3422. * @param right defines the right operand
  3423. * @returns the dot product
  3424. */
  3425. Vector3.Dot = function (left, right) {
  3426. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3427. };
  3428. /**
  3429. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3430. * The cross product is then orthogonal to both "left" and "right"
  3431. * @param left defines the left operand
  3432. * @param right defines the right operand
  3433. * @returns the cross product
  3434. */
  3435. Vector3.Cross = function (left, right) {
  3436. var result = Vector3.Zero();
  3437. Vector3.CrossToRef(left, right, result);
  3438. return result;
  3439. };
  3440. /**
  3441. * Sets the passed vector "result" with the cross product of "left" and "right"
  3442. * The cross product is then orthogonal to both "left" and "right"
  3443. * @param left defines the left operand
  3444. * @param right defines the right operand
  3445. * @param result defines the Vector3 where to store the result
  3446. */
  3447. Vector3.CrossToRef = function (left, right, result) {
  3448. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3449. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3450. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3451. result.copyFrom(MathTmp.Vector3[0]);
  3452. };
  3453. /**
  3454. * Returns a new Vector3 as the normalization of the passed vector
  3455. * @param vector defines the Vector3 to normalize
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Normalize = function (vector) {
  3459. var result = Vector3.Zero();
  3460. Vector3.NormalizeToRef(vector, result);
  3461. return result;
  3462. };
  3463. /**
  3464. * Sets the passed vector "result" with the normalization of the passed first vector
  3465. * @param vector defines the Vector3 to normalize
  3466. * @param result defines the Vector3 where to store the result
  3467. */
  3468. Vector3.NormalizeToRef = function (vector, result) {
  3469. result.copyFrom(vector);
  3470. result.normalize();
  3471. };
  3472. /**
  3473. * Project a Vector3 onto screen space
  3474. * @param vector defines the Vector3 to project
  3475. * @param world defines the world matrix to use
  3476. * @param transform defines the transform (view x projection) matrix to use
  3477. * @param viewport defines the screen viewport to use
  3478. * @returns the new Vector3
  3479. */
  3480. Vector3.Project = function (vector, world, transform, viewport) {
  3481. var cw = viewport.width;
  3482. var ch = viewport.height;
  3483. var cx = viewport.x;
  3484. var cy = viewport.y;
  3485. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3486. 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);
  3487. var matrix = MathTmp.Matrix[0];
  3488. world.multiplyToRef(transform, matrix);
  3489. matrix.multiplyToRef(viewportMatrix, matrix);
  3490. return Vector3.TransformCoordinates(vector, matrix);
  3491. };
  3492. /**
  3493. * Unproject from screen space to object space
  3494. * @param source defines the screen space Vector3 to use
  3495. * @param viewportWidth defines the current width of the viewport
  3496. * @param viewportHeight defines the current height of the viewport
  3497. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3498. * @param transform defines the transform (view x projection) matrix to use
  3499. * @returns the new Vector3
  3500. */
  3501. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3502. var matrix = MathTmp.Matrix[0];
  3503. world.multiplyToRef(transform, matrix);
  3504. matrix.invert();
  3505. source.x = source.x / viewportWidth * 2 - 1;
  3506. source.y = -(source.y / viewportHeight * 2 - 1);
  3507. var vector = Vector3.TransformCoordinates(source, matrix);
  3508. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3509. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3510. vector = vector.scale(1.0 / num);
  3511. }
  3512. return vector;
  3513. };
  3514. /**
  3515. * Unproject from screen space to object space
  3516. * @param source defines the screen space Vector3 to use
  3517. * @param viewportWidth defines the current width of the viewport
  3518. * @param viewportHeight defines the current height of the viewport
  3519. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3520. * @param view defines the view matrix to use
  3521. * @param projection defines the projection matrix to use
  3522. * @returns the new Vector3
  3523. */
  3524. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3525. var result = Vector3.Zero();
  3526. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3527. return result;
  3528. };
  3529. /**
  3530. * Unproject from screen space to object space
  3531. * @param source defines the screen space Vector3 to use
  3532. * @param viewportWidth defines the current width of the viewport
  3533. * @param viewportHeight defines the current height of the viewport
  3534. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3535. * @param view defines the view matrix to use
  3536. * @param projection defines the projection matrix to use
  3537. * @param result defines the Vector3 where to store the result
  3538. */
  3539. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3540. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3541. };
  3542. /**
  3543. * Unproject from screen space to object space
  3544. * @param sourceX defines the screen space x coordinate to use
  3545. * @param sourceY defines the screen space y coordinate to use
  3546. * @param sourceZ defines the screen space z coordinate to use
  3547. * @param viewportWidth defines the current width of the viewport
  3548. * @param viewportHeight defines the current height of the viewport
  3549. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3550. * @param view defines the view matrix to use
  3551. * @param projection defines the projection matrix to use
  3552. * @param result defines the Vector3 where to store the result
  3553. */
  3554. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3555. var matrix = MathTmp.Matrix[0];
  3556. world.multiplyToRef(view, matrix);
  3557. matrix.multiplyToRef(projection, matrix);
  3558. matrix.invert();
  3559. var screenSource = MathTmp.Vector3[0];
  3560. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3561. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3562. screenSource.z = 2 * sourceZ - 1.0;
  3563. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3564. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3565. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3566. result.scaleInPlace(1.0 / num);
  3567. }
  3568. };
  3569. /**
  3570. * Gets the minimal coordinate values between two Vector3
  3571. * @param left defines the first operand
  3572. * @param right defines the second operand
  3573. * @returns the new Vector3
  3574. */
  3575. Vector3.Minimize = function (left, right) {
  3576. var min = left.clone();
  3577. min.minimizeInPlace(right);
  3578. return min;
  3579. };
  3580. /**
  3581. * Gets the maximal coordinate values between two Vector3
  3582. * @param left defines the first operand
  3583. * @param right defines the second operand
  3584. * @returns the new Vector3
  3585. */
  3586. Vector3.Maximize = function (left, right) {
  3587. var max = left.clone();
  3588. max.maximizeInPlace(right);
  3589. return max;
  3590. };
  3591. /**
  3592. * Returns the distance between the vectors "value1" and "value2"
  3593. * @param value1 defines the first operand
  3594. * @param value2 defines the second operand
  3595. * @returns the distance
  3596. */
  3597. Vector3.Distance = function (value1, value2) {
  3598. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3599. };
  3600. /**
  3601. * Returns the squared distance between the vectors "value1" and "value2"
  3602. * @param value1 defines the first operand
  3603. * @param value2 defines the second operand
  3604. * @returns the squared distance
  3605. */
  3606. Vector3.DistanceSquared = function (value1, value2) {
  3607. var x = value1.x - value2.x;
  3608. var y = value1.y - value2.y;
  3609. var z = value1.z - value2.z;
  3610. return (x * x) + (y * y) + (z * z);
  3611. };
  3612. /**
  3613. * Returns a new Vector3 located at the center between "value1" and "value2"
  3614. * @param value1 defines the first operand
  3615. * @param value2 defines the second operand
  3616. * @returns the new Vector3
  3617. */
  3618. Vector3.Center = function (value1, value2) {
  3619. var center = value1.add(value2);
  3620. center.scaleInPlace(0.5);
  3621. return center;
  3622. };
  3623. /**
  3624. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3625. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3626. * to something in order to rotate it from its local system to the given target system
  3627. * Note: axis1, axis2 and axis3 are normalized during this operation
  3628. * @param axis1 defines the first axis
  3629. * @param axis2 defines the second axis
  3630. * @param axis3 defines the third axis
  3631. * @returns a new Vector3
  3632. */
  3633. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3634. var rotation = Vector3.Zero();
  3635. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3636. return rotation;
  3637. };
  3638. /**
  3639. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3640. * @param axis1 defines the first axis
  3641. * @param axis2 defines the second axis
  3642. * @param axis3 defines the third axis
  3643. * @param ref defines the Vector3 where to store the result
  3644. */
  3645. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3646. var quat = MathTmp.Quaternion[0];
  3647. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3648. quat.toEulerAnglesToRef(ref);
  3649. };
  3650. return Vector3;
  3651. }());
  3652. BABYLON.Vector3 = Vector3;
  3653. //Vector4 class created for EulerAngle class conversion to Quaternion
  3654. var Vector4 = /** @class */ (function () {
  3655. /**
  3656. * Creates a Vector4 object from the passed floats.
  3657. */
  3658. function Vector4(x, y, z, w) {
  3659. this.x = x;
  3660. this.y = y;
  3661. this.z = z;
  3662. this.w = w;
  3663. }
  3664. /**
  3665. * Returns the string with the Vector4 coordinates.
  3666. */
  3667. Vector4.prototype.toString = function () {
  3668. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3669. };
  3670. /**
  3671. * Returns the string "Vector4".
  3672. */
  3673. Vector4.prototype.getClassName = function () {
  3674. return "Vector4";
  3675. };
  3676. /**
  3677. * Returns the Vector4 hash code.
  3678. */
  3679. Vector4.prototype.getHashCode = function () {
  3680. var hash = this.x || 0;
  3681. hash = (hash * 397) ^ (this.y || 0);
  3682. hash = (hash * 397) ^ (this.z || 0);
  3683. hash = (hash * 397) ^ (this.w || 0);
  3684. return hash;
  3685. };
  3686. // Operators
  3687. /**
  3688. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3689. */
  3690. Vector4.prototype.asArray = function () {
  3691. var result = new Array();
  3692. this.toArray(result, 0);
  3693. return result;
  3694. };
  3695. /**
  3696. * Populates the passed array from the passed index with the Vector4 coordinates.
  3697. * Returns the Vector4.
  3698. */
  3699. Vector4.prototype.toArray = function (array, index) {
  3700. if (index === undefined) {
  3701. index = 0;
  3702. }
  3703. array[index] = this.x;
  3704. array[index + 1] = this.y;
  3705. array[index + 2] = this.z;
  3706. array[index + 3] = this.w;
  3707. return this;
  3708. };
  3709. /**
  3710. * Adds the passed vector to the current Vector4.
  3711. * Returns the updated Vector4.
  3712. */
  3713. Vector4.prototype.addInPlace = function (otherVector) {
  3714. this.x += otherVector.x;
  3715. this.y += otherVector.y;
  3716. this.z += otherVector.z;
  3717. this.w += otherVector.w;
  3718. return this;
  3719. };
  3720. /**
  3721. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3722. */
  3723. Vector4.prototype.add = function (otherVector) {
  3724. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3725. };
  3726. /**
  3727. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3728. * Returns the current Vector4.
  3729. */
  3730. Vector4.prototype.addToRef = function (otherVector, result) {
  3731. result.x = this.x + otherVector.x;
  3732. result.y = this.y + otherVector.y;
  3733. result.z = this.z + otherVector.z;
  3734. result.w = this.w + otherVector.w;
  3735. return this;
  3736. };
  3737. /**
  3738. * Subtract in place the passed vector from the current Vector4.
  3739. * Returns the updated Vector4.
  3740. */
  3741. Vector4.prototype.subtractInPlace = function (otherVector) {
  3742. this.x -= otherVector.x;
  3743. this.y -= otherVector.y;
  3744. this.z -= otherVector.z;
  3745. this.w -= otherVector.w;
  3746. return this;
  3747. };
  3748. /**
  3749. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3750. */
  3751. Vector4.prototype.subtract = function (otherVector) {
  3752. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3753. };
  3754. /**
  3755. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3756. * Returns the current Vector4.
  3757. */
  3758. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3759. result.x = this.x - otherVector.x;
  3760. result.y = this.y - otherVector.y;
  3761. result.z = this.z - otherVector.z;
  3762. result.w = this.w - otherVector.w;
  3763. return this;
  3764. };
  3765. /**
  3766. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3767. */
  3768. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3769. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3770. };
  3771. /**
  3772. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3773. * Returns the current Vector4.
  3774. */
  3775. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3776. result.x = this.x - x;
  3777. result.y = this.y - y;
  3778. result.z = this.z - z;
  3779. result.w = this.w - w;
  3780. return this;
  3781. };
  3782. /**
  3783. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3784. */
  3785. Vector4.prototype.negate = function () {
  3786. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3787. };
  3788. /**
  3789. * Multiplies the current Vector4 coordinates by scale (float).
  3790. * Returns the updated Vector4.
  3791. */
  3792. Vector4.prototype.scaleInPlace = function (scale) {
  3793. this.x *= scale;
  3794. this.y *= scale;
  3795. this.z *= scale;
  3796. this.w *= scale;
  3797. return this;
  3798. };
  3799. /**
  3800. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3801. */
  3802. Vector4.prototype.scale = function (scale) {
  3803. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3804. };
  3805. /**
  3806. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3807. * Returns the current Vector4.
  3808. */
  3809. Vector4.prototype.scaleToRef = function (scale, result) {
  3810. result.x = this.x * scale;
  3811. result.y = this.y * scale;
  3812. result.z = this.z * scale;
  3813. result.w = this.w * scale;
  3814. return this;
  3815. };
  3816. /**
  3817. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3818. * @param scale defines the scale factor
  3819. * @param result defines the Vector4 object where to store the result
  3820. * @returns the unmodified current Vector4
  3821. */
  3822. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3823. result.x += this.x * scale;
  3824. result.y += this.y * scale;
  3825. result.z += this.z * scale;
  3826. result.w += this.w * scale;
  3827. return this;
  3828. };
  3829. /**
  3830. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3831. */
  3832. Vector4.prototype.equals = function (otherVector) {
  3833. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3834. };
  3835. /**
  3836. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3837. */
  3838. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3839. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3840. return otherVector
  3841. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3842. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3843. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3844. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3845. };
  3846. /**
  3847. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3848. */
  3849. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3850. return this.x === x && this.y === y && this.z === z && this.w === w;
  3851. };
  3852. /**
  3853. * Multiplies in place the current Vector4 by the passed one.
  3854. * Returns the updated Vector4.
  3855. */
  3856. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3857. this.x *= otherVector.x;
  3858. this.y *= otherVector.y;
  3859. this.z *= otherVector.z;
  3860. this.w *= otherVector.w;
  3861. return this;
  3862. };
  3863. /**
  3864. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3865. */
  3866. Vector4.prototype.multiply = function (otherVector) {
  3867. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3868. };
  3869. /**
  3870. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3871. * Returns the current Vector4.
  3872. */
  3873. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3874. result.x = this.x * otherVector.x;
  3875. result.y = this.y * otherVector.y;
  3876. result.z = this.z * otherVector.z;
  3877. result.w = this.w * otherVector.w;
  3878. return this;
  3879. };
  3880. /**
  3881. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3882. */
  3883. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3884. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3885. };
  3886. /**
  3887. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3888. */
  3889. Vector4.prototype.divide = function (otherVector) {
  3890. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3891. };
  3892. /**
  3893. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3894. * Returns the current Vector4.
  3895. */
  3896. Vector4.prototype.divideToRef = function (otherVector, result) {
  3897. result.x = this.x / otherVector.x;
  3898. result.y = this.y / otherVector.y;
  3899. result.z = this.z / otherVector.z;
  3900. result.w = this.w / otherVector.w;
  3901. return this;
  3902. };
  3903. /**
  3904. * Divides the current Vector3 coordinates by the passed ones.
  3905. * @returns the updated Vector3.
  3906. */
  3907. Vector4.prototype.divideInPlace = function (otherVector) {
  3908. return this.divideToRef(otherVector, this);
  3909. };
  3910. /**
  3911. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3912. * @param other defines the second operand
  3913. * @returns the current updated Vector4
  3914. */
  3915. Vector4.prototype.minimizeInPlace = function (other) {
  3916. if (other.x < this.x)
  3917. this.x = other.x;
  3918. if (other.y < this.y)
  3919. this.y = other.y;
  3920. if (other.z < this.z)
  3921. this.z = other.z;
  3922. if (other.w < this.w)
  3923. this.w = other.w;
  3924. return this;
  3925. };
  3926. /**
  3927. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3928. * @param other defines the second operand
  3929. * @returns the current updated Vector4
  3930. */
  3931. Vector4.prototype.maximizeInPlace = function (other) {
  3932. if (other.x > this.x)
  3933. this.x = other.x;
  3934. if (other.y > this.y)
  3935. this.y = other.y;
  3936. if (other.z > this.z)
  3937. this.z = other.z;
  3938. if (other.w > this.w)
  3939. this.w = other.w;
  3940. return this;
  3941. };
  3942. // Properties
  3943. /**
  3944. * Returns the Vector4 length (float).
  3945. */
  3946. Vector4.prototype.length = function () {
  3947. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3948. };
  3949. /**
  3950. * Returns the Vector4 squared length (float).
  3951. */
  3952. Vector4.prototype.lengthSquared = function () {
  3953. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3954. };
  3955. // Methods
  3956. /**
  3957. * Normalizes in place the Vector4.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.normalize = function () {
  3961. var len = this.length();
  3962. if (len === 0)
  3963. return this;
  3964. var num = 1.0 / len;
  3965. this.x *= num;
  3966. this.y *= num;
  3967. this.z *= num;
  3968. this.w *= num;
  3969. return this;
  3970. };
  3971. /**
  3972. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3973. */
  3974. Vector4.prototype.toVector3 = function () {
  3975. return new Vector3(this.x, this.y, this.z);
  3976. };
  3977. /**
  3978. * Returns a new Vector4 copied from the current one.
  3979. */
  3980. Vector4.prototype.clone = function () {
  3981. return new Vector4(this.x, this.y, this.z, this.w);
  3982. };
  3983. /**
  3984. * Updates the current Vector4 with the passed one coordinates.
  3985. * Returns the updated Vector4.
  3986. */
  3987. Vector4.prototype.copyFrom = function (source) {
  3988. this.x = source.x;
  3989. this.y = source.y;
  3990. this.z = source.z;
  3991. this.w = source.w;
  3992. return this;
  3993. };
  3994. /**
  3995. * Updates the current Vector4 coordinates with the passed floats.
  3996. * Returns the updated Vector4.
  3997. */
  3998. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3999. this.x = x;
  4000. this.y = y;
  4001. this.z = z;
  4002. this.w = w;
  4003. return this;
  4004. };
  4005. /**
  4006. * Updates the current Vector4 coordinates with the passed floats.
  4007. * Returns the updated Vector4.
  4008. */
  4009. Vector4.prototype.set = function (x, y, z, w) {
  4010. return this.copyFromFloats(x, y, z, w);
  4011. };
  4012. // Statics
  4013. /**
  4014. * Returns a new Vector4 set from the starting index of the passed array.
  4015. */
  4016. Vector4.FromArray = function (array, offset) {
  4017. if (!offset) {
  4018. offset = 0;
  4019. }
  4020. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4021. };
  4022. /**
  4023. * Updates the passed vector "result" from the starting index of the passed array.
  4024. */
  4025. Vector4.FromArrayToRef = function (array, offset, result) {
  4026. result.x = array[offset];
  4027. result.y = array[offset + 1];
  4028. result.z = array[offset + 2];
  4029. result.w = array[offset + 3];
  4030. };
  4031. /**
  4032. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4033. */
  4034. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4035. Vector4.FromArrayToRef(array, offset, result);
  4036. };
  4037. /**
  4038. * Updates the passed vector "result" coordinates from the passed floats.
  4039. */
  4040. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4041. result.x = x;
  4042. result.y = y;
  4043. result.z = z;
  4044. result.w = w;
  4045. };
  4046. /**
  4047. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4048. */
  4049. Vector4.Zero = function () {
  4050. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4051. };
  4052. /**
  4053. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4054. */
  4055. Vector4.One = function () {
  4056. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4057. };
  4058. /**
  4059. * Returns a new normalized Vector4 from the passed one.
  4060. */
  4061. Vector4.Normalize = function (vector) {
  4062. var result = Vector4.Zero();
  4063. Vector4.NormalizeToRef(vector, result);
  4064. return result;
  4065. };
  4066. /**
  4067. * Updates the passed vector "result" from the normalization of the passed one.
  4068. */
  4069. Vector4.NormalizeToRef = function (vector, result) {
  4070. result.copyFrom(vector);
  4071. result.normalize();
  4072. };
  4073. Vector4.Minimize = function (left, right) {
  4074. var min = left.clone();
  4075. min.minimizeInPlace(right);
  4076. return min;
  4077. };
  4078. Vector4.Maximize = function (left, right) {
  4079. var max = left.clone();
  4080. max.maximizeInPlace(right);
  4081. return max;
  4082. };
  4083. /**
  4084. * Returns the distance (float) between the vectors "value1" and "value2".
  4085. */
  4086. Vector4.Distance = function (value1, value2) {
  4087. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4088. };
  4089. /**
  4090. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4091. */
  4092. Vector4.DistanceSquared = function (value1, value2) {
  4093. var x = value1.x - value2.x;
  4094. var y = value1.y - value2.y;
  4095. var z = value1.z - value2.z;
  4096. var w = value1.w - value2.w;
  4097. return (x * x) + (y * y) + (z * z) + (w * w);
  4098. };
  4099. /**
  4100. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4101. */
  4102. Vector4.Center = function (value1, value2) {
  4103. var center = value1.add(value2);
  4104. center.scaleInPlace(0.5);
  4105. return center;
  4106. };
  4107. /**
  4108. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4109. * This methods computes transformed normalized direction vectors only.
  4110. */
  4111. Vector4.TransformNormal = function (vector, transformation) {
  4112. var result = Vector4.Zero();
  4113. Vector4.TransformNormalToRef(vector, transformation, result);
  4114. return result;
  4115. };
  4116. /**
  4117. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4118. * This methods computes transformed normalized direction vectors only.
  4119. */
  4120. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4121. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4122. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4123. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4124. result.x = x;
  4125. result.y = y;
  4126. result.z = z;
  4127. result.w = vector.w;
  4128. };
  4129. /**
  4130. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4131. * This methods computes transformed normalized direction vectors only.
  4132. */
  4133. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4134. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4135. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4136. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4137. result.w = w;
  4138. };
  4139. return Vector4;
  4140. }());
  4141. BABYLON.Vector4 = Vector4;
  4142. var Size = /** @class */ (function () {
  4143. /**
  4144. * Creates a Size object from the passed width and height (floats).
  4145. */
  4146. function Size(width, height) {
  4147. this.width = width;
  4148. this.height = height;
  4149. }
  4150. // Returns a string with the Size width and height.
  4151. Size.prototype.toString = function () {
  4152. return "{W: " + this.width + ", H: " + this.height + "}";
  4153. };
  4154. /**
  4155. * Returns the string "Size"
  4156. */
  4157. Size.prototype.getClassName = function () {
  4158. return "Size";
  4159. };
  4160. /**
  4161. * Returns the Size hash code.
  4162. */
  4163. Size.prototype.getHashCode = function () {
  4164. var hash = this.width || 0;
  4165. hash = (hash * 397) ^ (this.height || 0);
  4166. return hash;
  4167. };
  4168. /**
  4169. * Updates the current size from the passed one.
  4170. * Returns the updated Size.
  4171. */
  4172. Size.prototype.copyFrom = function (src) {
  4173. this.width = src.width;
  4174. this.height = src.height;
  4175. };
  4176. /**
  4177. * Updates in place the current Size from the passed floats.
  4178. * Returns the updated Size.
  4179. */
  4180. Size.prototype.copyFromFloats = function (width, height) {
  4181. this.width = width;
  4182. this.height = height;
  4183. return this;
  4184. };
  4185. /**
  4186. * Updates in place the current Size from the passed floats.
  4187. * Returns the updated Size.
  4188. */
  4189. Size.prototype.set = function (width, height) {
  4190. return this.copyFromFloats(width, height);
  4191. };
  4192. /**
  4193. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4194. */
  4195. Size.prototype.multiplyByFloats = function (w, h) {
  4196. return new Size(this.width * w, this.height * h);
  4197. };
  4198. /**
  4199. * Returns a new Size copied from the passed one.
  4200. */
  4201. Size.prototype.clone = function () {
  4202. return new Size(this.width, this.height);
  4203. };
  4204. /**
  4205. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4206. */
  4207. Size.prototype.equals = function (other) {
  4208. if (!other) {
  4209. return false;
  4210. }
  4211. return (this.width === other.width) && (this.height === other.height);
  4212. };
  4213. Object.defineProperty(Size.prototype, "surface", {
  4214. /**
  4215. * Returns the surface of the Size : width * height (float).
  4216. */
  4217. get: function () {
  4218. return this.width * this.height;
  4219. },
  4220. enumerable: true,
  4221. configurable: true
  4222. });
  4223. /**
  4224. * Returns a new Size set to (0.0, 0.0)
  4225. */
  4226. Size.Zero = function () {
  4227. return new Size(0.0, 0.0);
  4228. };
  4229. /**
  4230. * Returns a new Size set as the addition result of the current Size and the passed one.
  4231. */
  4232. Size.prototype.add = function (otherSize) {
  4233. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4234. return r;
  4235. };
  4236. /**
  4237. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4238. */
  4239. Size.prototype.subtract = function (otherSize) {
  4240. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4241. return r;
  4242. };
  4243. /**
  4244. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4245. */
  4246. Size.Lerp = function (start, end, amount) {
  4247. var w = start.width + ((end.width - start.width) * amount);
  4248. var h = start.height + ((end.height - start.height) * amount);
  4249. return new Size(w, h);
  4250. };
  4251. return Size;
  4252. }());
  4253. BABYLON.Size = Size;
  4254. var Quaternion = /** @class */ (function () {
  4255. /**
  4256. * Creates a new Quaternion from the passed floats.
  4257. */
  4258. function Quaternion(x, y, z, w) {
  4259. if (x === void 0) { x = 0.0; }
  4260. if (y === void 0) { y = 0.0; }
  4261. if (z === void 0) { z = 0.0; }
  4262. if (w === void 0) { w = 1.0; }
  4263. this.x = x;
  4264. this.y = y;
  4265. this.z = z;
  4266. this.w = w;
  4267. }
  4268. /**
  4269. * Returns a string with the Quaternion coordinates.
  4270. */
  4271. Quaternion.prototype.toString = function () {
  4272. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4273. };
  4274. /**
  4275. * Returns the string "Quaternion".
  4276. */
  4277. Quaternion.prototype.getClassName = function () {
  4278. return "Quaternion";
  4279. };
  4280. /**
  4281. * Returns the Quaternion hash code.
  4282. */
  4283. Quaternion.prototype.getHashCode = function () {
  4284. var hash = this.x || 0;
  4285. hash = (hash * 397) ^ (this.y || 0);
  4286. hash = (hash * 397) ^ (this.z || 0);
  4287. hash = (hash * 397) ^ (this.w || 0);
  4288. return hash;
  4289. };
  4290. /**
  4291. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4292. */
  4293. Quaternion.prototype.asArray = function () {
  4294. return [this.x, this.y, this.z, this.w];
  4295. };
  4296. /**
  4297. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4298. */
  4299. Quaternion.prototype.equals = function (otherQuaternion) {
  4300. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4301. };
  4302. /**
  4303. * Returns a new Quaternion copied from the current one.
  4304. */
  4305. Quaternion.prototype.clone = function () {
  4306. return new Quaternion(this.x, this.y, this.z, this.w);
  4307. };
  4308. /**
  4309. * Updates the current Quaternion from the passed one coordinates.
  4310. * Returns the updated Quaterion.
  4311. */
  4312. Quaternion.prototype.copyFrom = function (other) {
  4313. this.x = other.x;
  4314. this.y = other.y;
  4315. this.z = other.z;
  4316. this.w = other.w;
  4317. return this;
  4318. };
  4319. /**
  4320. * Updates the current Quaternion from the passed float coordinates.
  4321. * Returns the updated Quaterion.
  4322. */
  4323. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4324. this.x = x;
  4325. this.y = y;
  4326. this.z = z;
  4327. this.w = w;
  4328. return this;
  4329. };
  4330. /**
  4331. * Updates the current Quaternion from the passed float coordinates.
  4332. * Returns the updated Quaterion.
  4333. */
  4334. Quaternion.prototype.set = function (x, y, z, w) {
  4335. return this.copyFromFloats(x, y, z, w);
  4336. };
  4337. /**
  4338. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4339. */
  4340. Quaternion.prototype.add = function (other) {
  4341. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4342. };
  4343. /**
  4344. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4345. */
  4346. Quaternion.prototype.subtract = function (other) {
  4347. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4348. };
  4349. /**
  4350. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4351. */
  4352. Quaternion.prototype.scale = function (value) {
  4353. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4354. };
  4355. /**
  4356. * Scale the current Quaternion values by a factor to a given Quaternion
  4357. * @param scale defines the scale factor
  4358. * @param result defines the Quaternion object where to store the result
  4359. * @returns the unmodified current Quaternion
  4360. */
  4361. Quaternion.prototype.scaleToRef = function (scale, result) {
  4362. result.x = this.x * scale;
  4363. result.y = this.y * scale;
  4364. result.z = this.z * scale;
  4365. result.w = this.w * scale;
  4366. return this;
  4367. };
  4368. /**
  4369. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4370. * @param scale defines the scale factor
  4371. * @param result defines the Quaternion object where to store the result
  4372. * @returns the unmodified current Quaternion
  4373. */
  4374. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4375. result.x += this.x * scale;
  4376. result.y += this.y * scale;
  4377. result.z += this.z * scale;
  4378. result.w += this.w * scale;
  4379. return this;
  4380. };
  4381. /**
  4382. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4383. */
  4384. Quaternion.prototype.multiply = function (q1) {
  4385. var result = new Quaternion(0, 0, 0, 1.0);
  4386. this.multiplyToRef(q1, result);
  4387. return result;
  4388. };
  4389. /**
  4390. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4391. * Returns the current Quaternion.
  4392. */
  4393. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4394. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4395. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4396. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4397. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4398. result.copyFromFloats(x, y, z, w);
  4399. return this;
  4400. };
  4401. /**
  4402. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4403. * Returns the updated Quaternion.
  4404. */
  4405. Quaternion.prototype.multiplyInPlace = function (q1) {
  4406. this.multiplyToRef(q1, this);
  4407. return this;
  4408. };
  4409. /**
  4410. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4411. * Returns the current Quaternion.
  4412. */
  4413. Quaternion.prototype.conjugateToRef = function (ref) {
  4414. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4415. return this;
  4416. };
  4417. /**
  4418. * Conjugates in place the current Quaternion.
  4419. * Returns the updated Quaternion.
  4420. */
  4421. Quaternion.prototype.conjugateInPlace = function () {
  4422. this.x *= -1;
  4423. this.y *= -1;
  4424. this.z *= -1;
  4425. return this;
  4426. };
  4427. /**
  4428. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4429. */
  4430. Quaternion.prototype.conjugate = function () {
  4431. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4432. return result;
  4433. };
  4434. /**
  4435. * Returns the Quaternion length (float).
  4436. */
  4437. Quaternion.prototype.length = function () {
  4438. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4439. };
  4440. /**
  4441. * Normalize in place the current Quaternion.
  4442. * Returns the updated Quaternion.
  4443. */
  4444. Quaternion.prototype.normalize = function () {
  4445. var length = 1.0 / this.length();
  4446. this.x *= length;
  4447. this.y *= length;
  4448. this.z *= length;
  4449. this.w *= length;
  4450. return this;
  4451. };
  4452. /**
  4453. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4454. * @param order is a reserved parameter and is ignore for now
  4455. * @returns the new Vector3
  4456. */
  4457. Quaternion.prototype.toEulerAngles = function (order) {
  4458. if (order === void 0) { order = "YZX"; }
  4459. var result = Vector3.Zero();
  4460. this.toEulerAnglesToRef(result, order);
  4461. return result;
  4462. };
  4463. /**
  4464. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4465. * @param result defines the vector which will be filled with the Euler angles
  4466. * @param order is a reserved parameter and is ignore for now
  4467. * @returns the current Quaternion
  4468. */
  4469. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4470. if (order === void 0) { order = "YZX"; }
  4471. var qz = this.z;
  4472. var qx = this.x;
  4473. var qy = this.y;
  4474. var qw = this.w;
  4475. var sqw = qw * qw;
  4476. var sqz = qz * qz;
  4477. var sqx = qx * qx;
  4478. var sqy = qy * qy;
  4479. var zAxisY = qy * qz - qx * qw;
  4480. var limit = .4999999;
  4481. if (zAxisY < -limit) {
  4482. result.y = 2 * Math.atan2(qy, qw);
  4483. result.x = Math.PI / 2;
  4484. result.z = 0;
  4485. }
  4486. else if (zAxisY > limit) {
  4487. result.y = 2 * Math.atan2(qy, qw);
  4488. result.x = -Math.PI / 2;
  4489. result.z = 0;
  4490. }
  4491. else {
  4492. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4493. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4494. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4495. }
  4496. return this;
  4497. };
  4498. /**
  4499. * Updates the passed rotation matrix with the current Quaternion values.
  4500. * Returns the current Quaternion.
  4501. */
  4502. Quaternion.prototype.toRotationMatrix = function (result) {
  4503. var xx = this.x * this.x;
  4504. var yy = this.y * this.y;
  4505. var zz = this.z * this.z;
  4506. var xy = this.x * this.y;
  4507. var zw = this.z * this.w;
  4508. var zx = this.z * this.x;
  4509. var yw = this.y * this.w;
  4510. var yz = this.y * this.z;
  4511. var xw = this.x * this.w;
  4512. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4513. result.m[1] = 2.0 * (xy + zw);
  4514. result.m[2] = 2.0 * (zx - yw);
  4515. result.m[3] = 0;
  4516. result.m[4] = 2.0 * (xy - zw);
  4517. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4518. result.m[6] = 2.0 * (yz + xw);
  4519. result.m[7] = 0;
  4520. result.m[8] = 2.0 * (zx + yw);
  4521. result.m[9] = 2.0 * (yz - xw);
  4522. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4523. result.m[11] = 0;
  4524. result.m[12] = 0;
  4525. result.m[13] = 0;
  4526. result.m[14] = 0;
  4527. result.m[15] = 1.0;
  4528. result._markAsUpdated();
  4529. return this;
  4530. };
  4531. /**
  4532. * Updates the current Quaternion from the passed rotation matrix values.
  4533. * Returns the updated Quaternion.
  4534. */
  4535. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4536. Quaternion.FromRotationMatrixToRef(matrix, this);
  4537. return this;
  4538. };
  4539. // Statics
  4540. /**
  4541. * Returns a new Quaternion set from the passed rotation matrix values.
  4542. */
  4543. Quaternion.FromRotationMatrix = function (matrix) {
  4544. var result = new Quaternion();
  4545. Quaternion.FromRotationMatrixToRef(matrix, result);
  4546. return result;
  4547. };
  4548. /**
  4549. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4550. */
  4551. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4552. var data = matrix.m;
  4553. var m11 = data[0], m12 = data[4], m13 = data[8];
  4554. var m21 = data[1], m22 = data[5], m23 = data[9];
  4555. var m31 = data[2], m32 = data[6], m33 = data[10];
  4556. var trace = m11 + m22 + m33;
  4557. var s;
  4558. if (trace > 0) {
  4559. s = 0.5 / Math.sqrt(trace + 1.0);
  4560. result.w = 0.25 / s;
  4561. result.x = (m32 - m23) * s;
  4562. result.y = (m13 - m31) * s;
  4563. result.z = (m21 - m12) * s;
  4564. }
  4565. else if (m11 > m22 && m11 > m33) {
  4566. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4567. result.w = (m32 - m23) / s;
  4568. result.x = 0.25 * s;
  4569. result.y = (m12 + m21) / s;
  4570. result.z = (m13 + m31) / s;
  4571. }
  4572. else if (m22 > m33) {
  4573. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4574. result.w = (m13 - m31) / s;
  4575. result.x = (m12 + m21) / s;
  4576. result.y = 0.25 * s;
  4577. result.z = (m23 + m32) / s;
  4578. }
  4579. else {
  4580. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4581. result.w = (m21 - m12) / s;
  4582. result.x = (m13 + m31) / s;
  4583. result.y = (m23 + m32) / s;
  4584. result.z = 0.25 * s;
  4585. }
  4586. };
  4587. /**
  4588. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4589. */
  4590. Quaternion.Zero = function () {
  4591. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4592. };
  4593. /**
  4594. * Returns a new Quaternion as the inverted current Quaternion.
  4595. */
  4596. Quaternion.Inverse = function (q) {
  4597. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4598. };
  4599. /**
  4600. * Returns the identity Quaternion.
  4601. */
  4602. Quaternion.Identity = function () {
  4603. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4604. };
  4605. Quaternion.IsIdentity = function (quaternion) {
  4606. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4607. };
  4608. /**
  4609. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4610. */
  4611. Quaternion.RotationAxis = function (axis, angle) {
  4612. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4613. };
  4614. /**
  4615. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4616. */
  4617. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4618. var sin = Math.sin(angle / 2);
  4619. axis.normalize();
  4620. result.w = Math.cos(angle / 2);
  4621. result.x = axis.x * sin;
  4622. result.y = axis.y * sin;
  4623. result.z = axis.z * sin;
  4624. return result;
  4625. };
  4626. /**
  4627. * Retuns a new Quaternion set from the starting index of the passed array.
  4628. */
  4629. Quaternion.FromArray = function (array, offset) {
  4630. if (!offset) {
  4631. offset = 0;
  4632. }
  4633. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4634. };
  4635. /**
  4636. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4637. */
  4638. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4639. var q = new Quaternion();
  4640. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4641. return q;
  4642. };
  4643. /**
  4644. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4645. */
  4646. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4647. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4648. var halfRoll = roll * 0.5;
  4649. var halfPitch = pitch * 0.5;
  4650. var halfYaw = yaw * 0.5;
  4651. var sinRoll = Math.sin(halfRoll);
  4652. var cosRoll = Math.cos(halfRoll);
  4653. var sinPitch = Math.sin(halfPitch);
  4654. var cosPitch = Math.cos(halfPitch);
  4655. var sinYaw = Math.sin(halfYaw);
  4656. var cosYaw = Math.cos(halfYaw);
  4657. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4658. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4659. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4660. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4661. };
  4662. /**
  4663. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4664. */
  4665. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4666. var result = new Quaternion();
  4667. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4668. return result;
  4669. };
  4670. /**
  4671. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4672. */
  4673. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4674. // Produces a quaternion from Euler angles in the z-x-z orientation
  4675. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4676. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4677. var halfBeta = beta * 0.5;
  4678. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4679. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4680. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4681. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4682. };
  4683. /**
  4684. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4685. * cf to Vector3.RotationFromAxis() documentation.
  4686. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4687. */
  4688. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4689. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4690. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4691. return quat;
  4692. };
  4693. /**
  4694. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4695. * cf to Vector3.RotationFromAxis() documentation.
  4696. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4697. */
  4698. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4699. var rotMat = MathTmp.Matrix[0];
  4700. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4701. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4702. };
  4703. Quaternion.Slerp = function (left, right, amount) {
  4704. var result = Quaternion.Identity();
  4705. Quaternion.SlerpToRef(left, right, amount, result);
  4706. return result;
  4707. };
  4708. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4709. var num2;
  4710. var num3;
  4711. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4712. var flag = false;
  4713. if (num4 < 0) {
  4714. flag = true;
  4715. num4 = -num4;
  4716. }
  4717. if (num4 > 0.999999) {
  4718. num3 = 1 - amount;
  4719. num2 = flag ? -amount : amount;
  4720. }
  4721. else {
  4722. var num5 = Math.acos(num4);
  4723. var num6 = (1.0 / Math.sin(num5));
  4724. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4725. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4726. }
  4727. result.x = (num3 * left.x) + (num2 * right.x);
  4728. result.y = (num3 * left.y) + (num2 * right.y);
  4729. result.z = (num3 * left.z) + (num2 * right.z);
  4730. result.w = (num3 * left.w) + (num2 * right.w);
  4731. };
  4732. /**
  4733. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4734. */
  4735. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4736. var squared = amount * amount;
  4737. var cubed = amount * squared;
  4738. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4739. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4740. var part3 = (cubed - (2.0 * squared)) + amount;
  4741. var part4 = cubed - squared;
  4742. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4743. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4744. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4745. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4746. return new Quaternion(x, y, z, w);
  4747. };
  4748. return Quaternion;
  4749. }());
  4750. BABYLON.Quaternion = Quaternion;
  4751. /**
  4752. * Class used to store matrix data (4x4)
  4753. */
  4754. var Matrix = /** @class */ (function () {
  4755. /**
  4756. * Creates an empty matrix (filled with zeros)
  4757. */
  4758. function Matrix() {
  4759. this._isIdentity = false;
  4760. this._isIdentityDirty = true;
  4761. /**
  4762. * Gets or sets the internal data of the matrix
  4763. */
  4764. this.m = new Float32Array(16);
  4765. this._markAsUpdated();
  4766. }
  4767. /** @ignore */
  4768. Matrix.prototype._markAsUpdated = function () {
  4769. this.updateFlag = Matrix._updateFlagSeed++;
  4770. this._isIdentityDirty = true;
  4771. };
  4772. // Properties
  4773. /**
  4774. * Check if the current matrix is indentity
  4775. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  4776. * @returns true is the matrix is the identity matrix
  4777. */
  4778. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4779. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4780. if (this._isIdentityDirty) {
  4781. this._isIdentityDirty = false;
  4782. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4783. this._isIdentity = false;
  4784. }
  4785. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4786. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4787. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4788. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4789. this._isIdentity = false;
  4790. }
  4791. else {
  4792. this._isIdentity = true;
  4793. }
  4794. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4795. this._isIdentity = false;
  4796. }
  4797. }
  4798. return this._isIdentity;
  4799. };
  4800. /**
  4801. * Gets the determinant of the matrix
  4802. * @returns the matrix determinant
  4803. */
  4804. Matrix.prototype.determinant = function () {
  4805. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4806. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4807. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4808. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4809. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4810. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4811. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4812. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4813. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4814. };
  4815. // Methods
  4816. /**
  4817. * Returns the matrix as a Float32Array
  4818. * @returns the matrix underlying array
  4819. */
  4820. Matrix.prototype.toArray = function () {
  4821. return this.m;
  4822. };
  4823. /**
  4824. * Returns the matrix as a Float32Array
  4825. * @returns the matrix underlying array.
  4826. */
  4827. Matrix.prototype.asArray = function () {
  4828. return this.toArray();
  4829. };
  4830. /**
  4831. * Inverts the current matrix in place
  4832. * @returns the current inverted matrix
  4833. */
  4834. Matrix.prototype.invert = function () {
  4835. this.invertToRef(this);
  4836. return this;
  4837. };
  4838. /**
  4839. * Sets all the matrix elements to zero
  4840. * @returns the current matrix
  4841. */
  4842. Matrix.prototype.reset = function () {
  4843. for (var index = 0; index < 16; index++) {
  4844. this.m[index] = 0.0;
  4845. }
  4846. this._markAsUpdated();
  4847. return this;
  4848. };
  4849. /**
  4850. * Adds the current matrix with a second one
  4851. * @param other defines the matrix to add
  4852. * @returns a new matrix as the addition of the current matrix and the passed one
  4853. */
  4854. Matrix.prototype.add = function (other) {
  4855. var result = new Matrix();
  4856. this.addToRef(other, result);
  4857. return result;
  4858. };
  4859. /**
  4860. * Sets the passed matrix "result" to the addition of the current matrix and the passed one
  4861. * @param other defines the matrix to add
  4862. * @param result defines the target matrix
  4863. * @returns the current matrix
  4864. */
  4865. Matrix.prototype.addToRef = function (other, result) {
  4866. for (var index = 0; index < 16; index++) {
  4867. result.m[index] = this.m[index] + other.m[index];
  4868. }
  4869. result._markAsUpdated();
  4870. return this;
  4871. };
  4872. /**
  4873. * Adds in place the passed matrix to the current matrix
  4874. * @param other defines the second operand
  4875. * @returns the current updated matrix
  4876. */
  4877. Matrix.prototype.addToSelf = function (other) {
  4878. for (var index = 0; index < 16; index++) {
  4879. this.m[index] += other.m[index];
  4880. }
  4881. this._markAsUpdated();
  4882. return this;
  4883. };
  4884. /**
  4885. * Sets the passed matrix to the current inverted Matrix
  4886. * @param other defines the target matrix
  4887. * @returns the unmodified current matrix
  4888. */
  4889. Matrix.prototype.invertToRef = function (other) {
  4890. var l1 = this.m[0];
  4891. var l2 = this.m[1];
  4892. var l3 = this.m[2];
  4893. var l4 = this.m[3];
  4894. var l5 = this.m[4];
  4895. var l6 = this.m[5];
  4896. var l7 = this.m[6];
  4897. var l8 = this.m[7];
  4898. var l9 = this.m[8];
  4899. var l10 = this.m[9];
  4900. var l11 = this.m[10];
  4901. var l12 = this.m[11];
  4902. var l13 = this.m[12];
  4903. var l14 = this.m[13];
  4904. var l15 = this.m[14];
  4905. var l16 = this.m[15];
  4906. var l17 = (l11 * l16) - (l12 * l15);
  4907. var l18 = (l10 * l16) - (l12 * l14);
  4908. var l19 = (l10 * l15) - (l11 * l14);
  4909. var l20 = (l9 * l16) - (l12 * l13);
  4910. var l21 = (l9 * l15) - (l11 * l13);
  4911. var l22 = (l9 * l14) - (l10 * l13);
  4912. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4913. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4914. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4915. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4916. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4917. var l28 = (l7 * l16) - (l8 * l15);
  4918. var l29 = (l6 * l16) - (l8 * l14);
  4919. var l30 = (l6 * l15) - (l7 * l14);
  4920. var l31 = (l5 * l16) - (l8 * l13);
  4921. var l32 = (l5 * l15) - (l7 * l13);
  4922. var l33 = (l5 * l14) - (l6 * l13);
  4923. var l34 = (l7 * l12) - (l8 * l11);
  4924. var l35 = (l6 * l12) - (l8 * l10);
  4925. var l36 = (l6 * l11) - (l7 * l10);
  4926. var l37 = (l5 * l12) - (l8 * l9);
  4927. var l38 = (l5 * l11) - (l7 * l9);
  4928. var l39 = (l5 * l10) - (l6 * l9);
  4929. other.m[0] = l23 * l27;
  4930. other.m[4] = l24 * l27;
  4931. other.m[8] = l25 * l27;
  4932. other.m[12] = l26 * l27;
  4933. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4934. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4935. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4936. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4937. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4938. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4939. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4940. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4941. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4942. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4943. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4944. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4945. other._markAsUpdated();
  4946. return this;
  4947. };
  4948. /**
  4949. * Inserts the translation vector (using 3 floats) in the current matrix
  4950. * @param x defines the 1st component of the translation
  4951. * @param y defines the 2nd component of the translation
  4952. * @param z defines the 3rd component of the translation
  4953. * @returns the current updated matrix
  4954. */
  4955. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4956. this.m[12] = x;
  4957. this.m[13] = y;
  4958. this.m[14] = z;
  4959. this._markAsUpdated();
  4960. return this;
  4961. };
  4962. /**
  4963. * Inserts the translation vector in the current matrix
  4964. * @param vector3 defines the translation to insert
  4965. * @returns the current updated matrix
  4966. */
  4967. Matrix.prototype.setTranslation = function (vector3) {
  4968. this.m[12] = vector3.x;
  4969. this.m[13] = vector3.y;
  4970. this.m[14] = vector3.z;
  4971. this._markAsUpdated();
  4972. return this;
  4973. };
  4974. /**
  4975. * Gets the translation value of the current matrix
  4976. * @returns a new Vector3 as the extracted translation from the matrix
  4977. */
  4978. Matrix.prototype.getTranslation = function () {
  4979. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4980. };
  4981. /**
  4982. * Fill a Vector3 with the extracted translation from the matrix
  4983. * @param result defines the Vector3 where to store the translation
  4984. * @returns the current matrix
  4985. */
  4986. Matrix.prototype.getTranslationToRef = function (result) {
  4987. result.x = this.m[12];
  4988. result.y = this.m[13];
  4989. result.z = this.m[14];
  4990. return this;
  4991. };
  4992. /**
  4993. * Remove rotation and scaling part from the matrix
  4994. * @returns the updated matrix
  4995. */
  4996. Matrix.prototype.removeRotationAndScaling = function () {
  4997. this.setRowFromFloats(0, 1, 0, 0, 0);
  4998. this.setRowFromFloats(1, 0, 1, 0, 0);
  4999. this.setRowFromFloats(2, 0, 0, 1, 0);
  5000. return this;
  5001. };
  5002. /**
  5003. * Multiply two matrices
  5004. * @param other defines the second operand
  5005. * @returns a new matrix set with the multiplication result of the current Matrix and the passed one
  5006. */
  5007. Matrix.prototype.multiply = function (other) {
  5008. var result = new Matrix();
  5009. this.multiplyToRef(other, result);
  5010. return result;
  5011. };
  5012. /**
  5013. * Copy the current matrix from the passed one
  5014. * @param other defines the source matrix
  5015. * @returns the current updated matrix
  5016. */
  5017. Matrix.prototype.copyFrom = function (other) {
  5018. for (var index = 0; index < 16; index++) {
  5019. this.m[index] = other.m[index];
  5020. }
  5021. this._markAsUpdated();
  5022. return this;
  5023. };
  5024. /**
  5025. * Populates the passed array from the starting index with the current matrix values
  5026. * @param array defines the target array
  5027. * @param offset defines the offset in the target array where to start storing values
  5028. * @returns the current matrix
  5029. */
  5030. Matrix.prototype.copyToArray = function (array, offset) {
  5031. if (offset === void 0) { offset = 0; }
  5032. for (var index = 0; index < 16; index++) {
  5033. array[offset + index] = this.m[index];
  5034. }
  5035. return this;
  5036. };
  5037. /**
  5038. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one
  5039. * @param other defines the second operand
  5040. * @param result defines the matrix where to store the multiplication
  5041. * @returns the current matrix
  5042. */
  5043. Matrix.prototype.multiplyToRef = function (other, result) {
  5044. this.multiplyToArray(other, result.m, 0);
  5045. result._markAsUpdated();
  5046. return this;
  5047. };
  5048. /**
  5049. * Sets the Float32Array "result" from the passed index "offset" with the multiplication of the current matrix and the passed one
  5050. * @param other defines the second operand
  5051. * @param result defines the array where to store the multiplication
  5052. * @param offset defines the offset in the target array where to start storing values
  5053. * @returns the current matrix
  5054. */
  5055. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5056. var tm0 = this.m[0];
  5057. var tm1 = this.m[1];
  5058. var tm2 = this.m[2];
  5059. var tm3 = this.m[3];
  5060. var tm4 = this.m[4];
  5061. var tm5 = this.m[5];
  5062. var tm6 = this.m[6];
  5063. var tm7 = this.m[7];
  5064. var tm8 = this.m[8];
  5065. var tm9 = this.m[9];
  5066. var tm10 = this.m[10];
  5067. var tm11 = this.m[11];
  5068. var tm12 = this.m[12];
  5069. var tm13 = this.m[13];
  5070. var tm14 = this.m[14];
  5071. var tm15 = this.m[15];
  5072. var om0 = other.m[0];
  5073. var om1 = other.m[1];
  5074. var om2 = other.m[2];
  5075. var om3 = other.m[3];
  5076. var om4 = other.m[4];
  5077. var om5 = other.m[5];
  5078. var om6 = other.m[6];
  5079. var om7 = other.m[7];
  5080. var om8 = other.m[8];
  5081. var om9 = other.m[9];
  5082. var om10 = other.m[10];
  5083. var om11 = other.m[11];
  5084. var om12 = other.m[12];
  5085. var om13 = other.m[13];
  5086. var om14 = other.m[14];
  5087. var om15 = other.m[15];
  5088. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5089. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5090. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5091. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5092. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5093. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5094. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5095. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5096. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5097. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5098. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5099. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5100. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5101. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5102. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5103. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5104. return this;
  5105. };
  5106. /**
  5107. * Check equality between this matrix and a second one
  5108. * @param value defines the second matrix to compare
  5109. * @returns true is the current matrix and the passed one values are strictly equal
  5110. */
  5111. Matrix.prototype.equals = function (value) {
  5112. return value &&
  5113. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5114. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5115. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5116. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5117. };
  5118. /**
  5119. * Clone the current matrix
  5120. * @returns a new matrix from the current matrix
  5121. */
  5122. Matrix.prototype.clone = function () {
  5123. 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]);
  5124. };
  5125. /**
  5126. * Returns the name of the current matrix class
  5127. * @returns the string "Matrix"
  5128. */
  5129. Matrix.prototype.getClassName = function () {
  5130. return "Matrix";
  5131. };
  5132. /**
  5133. * Gets the hash code of the current matrix
  5134. * @returns the hash code
  5135. */
  5136. Matrix.prototype.getHashCode = function () {
  5137. var hash = this.m[0] || 0;
  5138. for (var i = 1; i < 16; i++) {
  5139. hash = (hash * 397) ^ (this.m[i] || 0);
  5140. }
  5141. return hash;
  5142. };
  5143. /**
  5144. * Decomposes the current Matrix into a translation, rotation and scaling components
  5145. * @param scale defines the scale vector3 passed as a reference to update
  5146. * @param rotation defines the rotation quaternion passed as a reference to update
  5147. * @param translation defines the translation vector3 passed as a reference to update
  5148. * @returns true if operation was successful
  5149. */
  5150. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5151. if (translation) {
  5152. translation.x = this.m[12];
  5153. translation.y = this.m[13];
  5154. translation.z = this.m[14];
  5155. }
  5156. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5157. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5158. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5159. if (this.determinant() <= 0) {
  5160. scale.y *= -1;
  5161. }
  5162. if (rotation) {
  5163. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5164. rotation.x = 0;
  5165. rotation.y = 0;
  5166. rotation.z = 0;
  5167. rotation.w = 1;
  5168. return false;
  5169. }
  5170. 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]);
  5171. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5172. }
  5173. return true;
  5174. };
  5175. /**
  5176. * Gets specific row of the matrix
  5177. * @param index defines the number of the row to get
  5178. * @returns the index-th row of the current matrix as a new Vector4
  5179. */
  5180. Matrix.prototype.getRow = function (index) {
  5181. if (index < 0 || index > 3) {
  5182. return null;
  5183. }
  5184. var i = index * 4;
  5185. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5186. };
  5187. /**
  5188. * Sets the index-th row of the current matrix to the vector4 values
  5189. * @param index defines the number of the row to set
  5190. * @param row defines the target vector4
  5191. * @returns the updated current matrix
  5192. */
  5193. Matrix.prototype.setRow = function (index, row) {
  5194. if (index < 0 || index > 3) {
  5195. return this;
  5196. }
  5197. var i = index * 4;
  5198. this.m[i + 0] = row.x;
  5199. this.m[i + 1] = row.y;
  5200. this.m[i + 2] = row.z;
  5201. this.m[i + 3] = row.w;
  5202. this._markAsUpdated();
  5203. return this;
  5204. };
  5205. /**
  5206. * Compute the transpose of the matrix
  5207. * @returns the new transposed matrix
  5208. */
  5209. Matrix.prototype.transpose = function () {
  5210. return Matrix.Transpose(this);
  5211. };
  5212. /**
  5213. * Compute the transpose of the matrix and store it in a given matrix
  5214. * @param result defines the target matrix
  5215. * @returns the current matrix
  5216. */
  5217. Matrix.prototype.transposeToRef = function (result) {
  5218. Matrix.TransposeToRef(this, result);
  5219. return this;
  5220. };
  5221. /**
  5222. * Sets the index-th row of the current matrix with the passed 4 x float values
  5223. * @param index defines the row index
  5224. * @param x defines the x component to set
  5225. * @param y defines the y component to set
  5226. * @param z defines the z component to set
  5227. * @param w defines the w component to set
  5228. * @returns the updated current matrix
  5229. */
  5230. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5231. if (index < 0 || index > 3) {
  5232. return this;
  5233. }
  5234. var i = index * 4;
  5235. this.m[i + 0] = x;
  5236. this.m[i + 1] = y;
  5237. this.m[i + 2] = z;
  5238. this.m[i + 3] = w;
  5239. this._markAsUpdated();
  5240. return this;
  5241. };
  5242. /**
  5243. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5244. * @param scale defines the scale factor
  5245. * @returns a new matrix
  5246. */
  5247. Matrix.prototype.scale = function (scale) {
  5248. var result = new Matrix();
  5249. this.scaleToRef(scale, result);
  5250. return result;
  5251. };
  5252. /**
  5253. * Scale the current matrix values by a factor to a given result matrix
  5254. * @param scale defines the scale factor
  5255. * @param result defines the matrix to store the result
  5256. * @returns the current matrix
  5257. */
  5258. Matrix.prototype.scaleToRef = function (scale, result) {
  5259. for (var index = 0; index < 16; index++) {
  5260. result.m[index] = this.m[index] * scale;
  5261. }
  5262. result._markAsUpdated();
  5263. return this;
  5264. };
  5265. /**
  5266. * Scale the current matrix values by a factor and add the result to a given matrix
  5267. * @param scale defines the scale factor
  5268. * @param result defines the Matrix to store the result
  5269. * @returns the current matrix
  5270. */
  5271. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5272. for (var index = 0; index < 16; index++) {
  5273. result.m[index] += this.m[index] * scale;
  5274. }
  5275. result._markAsUpdated();
  5276. return this;
  5277. };
  5278. /**
  5279. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5280. * @param ref matrix to store the result
  5281. */
  5282. Matrix.prototype.toNormalMatrix = function (ref) {
  5283. this.invertToRef(ref);
  5284. ref.transpose();
  5285. var m = ref.m;
  5286. 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);
  5287. };
  5288. /**
  5289. * Gets only rotation part of the current matrix
  5290. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5291. */
  5292. Matrix.prototype.getRotationMatrix = function () {
  5293. var result = Matrix.Identity();
  5294. this.getRotationMatrixToRef(result);
  5295. return result;
  5296. };
  5297. /**
  5298. * Extracts the rotation matrix from the current one and sets it as the passed "result"
  5299. * @param result defines the target matrix to store data to
  5300. * @returns the current matrix
  5301. */
  5302. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5303. var m = this.m;
  5304. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5305. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5306. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5307. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5308. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5309. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5310. 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);
  5311. return this;
  5312. };
  5313. // Statics
  5314. /**
  5315. * Creates a matrix from an array
  5316. * @param array defines the source array
  5317. * @param offset defines an offset in the source array
  5318. * @returns a new Matrix set from the starting index of the passed array
  5319. */
  5320. Matrix.FromArray = function (array, offset) {
  5321. var result = new Matrix();
  5322. if (!offset) {
  5323. offset = 0;
  5324. }
  5325. Matrix.FromArrayToRef(array, offset, result);
  5326. return result;
  5327. };
  5328. /**
  5329. * Copy the content of an array into a given matrix
  5330. * @param array defines the source array
  5331. * @param offset defines an offset in the source array
  5332. * @param result defines the target matrix
  5333. */
  5334. Matrix.FromArrayToRef = function (array, offset, result) {
  5335. for (var index = 0; index < 16; index++) {
  5336. result.m[index] = array[index + offset];
  5337. }
  5338. result._markAsUpdated();
  5339. };
  5340. /**
  5341. * Stores an array into a matrix after having multiplied each component by a given factor
  5342. * @param array defines the source array
  5343. * @param offset defines the offset in the source array
  5344. * @param scale defines the scaling factor
  5345. * @param result defines the target matrix
  5346. */
  5347. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5348. for (var index = 0; index < 16; index++) {
  5349. result.m[index] = array[index + offset] * scale;
  5350. }
  5351. result._markAsUpdated();
  5352. };
  5353. /**
  5354. * Stores a list of values (16) inside a given matrix
  5355. * @param initialM11 defines 1st value of 1st row
  5356. * @param initialM12 defines 2nd value of 1st row
  5357. * @param initialM13 defines 3rd value of 1st row
  5358. * @param initialM14 defines 4th value of 1st row
  5359. * @param initialM21 defines 1st value of 2nd row
  5360. * @param initialM22 defines 2nd value of 2nd row
  5361. * @param initialM23 defines 3rd value of 2nd row
  5362. * @param initialM24 defines 4th value of 2nd row
  5363. * @param initialM31 defines 1st value of 3rd row
  5364. * @param initialM32 defines 2nd value of 3rd row
  5365. * @param initialM33 defines 3rd value of 3rd row
  5366. * @param initialM34 defines 4th value of 3rd row
  5367. * @param initialM41 defines 1st value of 4th row
  5368. * @param initialM42 defines 2nd value of 4th row
  5369. * @param initialM43 defines 3rd value of 4th row
  5370. * @param initialM44 defines 4th value of 4th row
  5371. * @param result defines the target matrix
  5372. */
  5373. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5374. result.m[0] = initialM11;
  5375. result.m[1] = initialM12;
  5376. result.m[2] = initialM13;
  5377. result.m[3] = initialM14;
  5378. result.m[4] = initialM21;
  5379. result.m[5] = initialM22;
  5380. result.m[6] = initialM23;
  5381. result.m[7] = initialM24;
  5382. result.m[8] = initialM31;
  5383. result.m[9] = initialM32;
  5384. result.m[10] = initialM33;
  5385. result.m[11] = initialM34;
  5386. result.m[12] = initialM41;
  5387. result.m[13] = initialM42;
  5388. result.m[14] = initialM43;
  5389. result.m[15] = initialM44;
  5390. result._markAsUpdated();
  5391. };
  5392. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5393. /**
  5394. * Gets an identity matrix that must not be updated
  5395. */
  5396. get: function () {
  5397. return Matrix._identityReadOnly;
  5398. },
  5399. enumerable: true,
  5400. configurable: true
  5401. });
  5402. /**
  5403. * Creates new matrix from a list of values (16)
  5404. * @param initialM11 defines 1st value of 1st row
  5405. * @param initialM12 defines 2nd value of 1st row
  5406. * @param initialM13 defines 3rd value of 1st row
  5407. * @param initialM14 defines 4th value of 1st row
  5408. * @param initialM21 defines 1st value of 2nd row
  5409. * @param initialM22 defines 2nd value of 2nd row
  5410. * @param initialM23 defines 3rd value of 2nd row
  5411. * @param initialM24 defines 4th value of 2nd row
  5412. * @param initialM31 defines 1st value of 3rd row
  5413. * @param initialM32 defines 2nd value of 3rd row
  5414. * @param initialM33 defines 3rd value of 3rd row
  5415. * @param initialM34 defines 4th value of 3rd row
  5416. * @param initialM41 defines 1st value of 4th row
  5417. * @param initialM42 defines 2nd value of 4th row
  5418. * @param initialM43 defines 3rd value of 4th row
  5419. * @param initialM44 defines 4th value of 4th row
  5420. * @returns the new matrix
  5421. */
  5422. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5423. var result = new Matrix();
  5424. result.m[0] = initialM11;
  5425. result.m[1] = initialM12;
  5426. result.m[2] = initialM13;
  5427. result.m[3] = initialM14;
  5428. result.m[4] = initialM21;
  5429. result.m[5] = initialM22;
  5430. result.m[6] = initialM23;
  5431. result.m[7] = initialM24;
  5432. result.m[8] = initialM31;
  5433. result.m[9] = initialM32;
  5434. result.m[10] = initialM33;
  5435. result.m[11] = initialM34;
  5436. result.m[12] = initialM41;
  5437. result.m[13] = initialM42;
  5438. result.m[14] = initialM43;
  5439. result.m[15] = initialM44;
  5440. return result;
  5441. };
  5442. /**
  5443. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5444. * @param scale defines the scale vector3
  5445. * @param rotation defines the rotation quaternion
  5446. * @param translation defines the translation vector3
  5447. * @returns a new matrix
  5448. */
  5449. Matrix.Compose = function (scale, rotation, translation) {
  5450. var result = Matrix.Identity();
  5451. Matrix.ComposeToRef(scale, rotation, translation, result);
  5452. return result;
  5453. };
  5454. /**
  5455. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5456. * @param scale defines the scale vector3
  5457. * @param rotation defines the rotation quaternion
  5458. * @param translation defines the translation vector3
  5459. * @param result defines the target matrix
  5460. */
  5461. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5462. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5463. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5464. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5465. result.setTranslation(translation);
  5466. };
  5467. /**
  5468. * Creates a new identity matrix
  5469. * @returns a new identity matrix
  5470. */
  5471. Matrix.Identity = function () {
  5472. 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);
  5473. };
  5474. /**
  5475. * Creates a new identity matrix and stores the result in a given matrix
  5476. * @param result defines the target matrix
  5477. */
  5478. Matrix.IdentityToRef = function (result) {
  5479. 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);
  5480. };
  5481. /**
  5482. * Creates a new zero matrix
  5483. * @returns a new zero matrix
  5484. */
  5485. Matrix.Zero = function () {
  5486. 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);
  5487. };
  5488. /**
  5489. * Creates a new rotation matrix for "angle" radians around the X axis
  5490. * @param angle defines the angle (in radians) to use
  5491. * @return the new matrix
  5492. */
  5493. Matrix.RotationX = function (angle) {
  5494. var result = new Matrix();
  5495. Matrix.RotationXToRef(angle, result);
  5496. return result;
  5497. };
  5498. /**
  5499. * Creates a new matrix as the invert of a given matrix
  5500. * @param source defines the source matrix
  5501. * @returns the new matrix
  5502. */
  5503. Matrix.Invert = function (source) {
  5504. var result = new Matrix();
  5505. source.invertToRef(result);
  5506. return result;
  5507. };
  5508. /**
  5509. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5510. * @param angle defines the angle (in radians) to use
  5511. * @param result defines the target matrix
  5512. */
  5513. Matrix.RotationXToRef = function (angle, result) {
  5514. var s = Math.sin(angle);
  5515. var c = Math.cos(angle);
  5516. result.m[0] = 1.0;
  5517. result.m[15] = 1.0;
  5518. result.m[5] = c;
  5519. result.m[10] = c;
  5520. result.m[9] = -s;
  5521. result.m[6] = s;
  5522. result.m[1] = 0.0;
  5523. result.m[2] = 0.0;
  5524. result.m[3] = 0.0;
  5525. result.m[4] = 0.0;
  5526. result.m[7] = 0.0;
  5527. result.m[8] = 0.0;
  5528. result.m[11] = 0.0;
  5529. result.m[12] = 0.0;
  5530. result.m[13] = 0.0;
  5531. result.m[14] = 0.0;
  5532. result._markAsUpdated();
  5533. };
  5534. /**
  5535. * Creates a new rotation matrix for "angle" radians around the Y axis
  5536. * @param angle defines the angle (in radians) to use
  5537. * @return the new matrix
  5538. */
  5539. Matrix.RotationY = function (angle) {
  5540. var result = new Matrix();
  5541. Matrix.RotationYToRef(angle, result);
  5542. return result;
  5543. };
  5544. /**
  5545. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5546. * @param angle defines the angle (in radians) to use
  5547. * @param result defines the target matrix
  5548. */
  5549. Matrix.RotationYToRef = function (angle, result) {
  5550. var s = Math.sin(angle);
  5551. var c = Math.cos(angle);
  5552. result.m[5] = 1.0;
  5553. result.m[15] = 1.0;
  5554. result.m[0] = c;
  5555. result.m[2] = -s;
  5556. result.m[8] = s;
  5557. result.m[10] = c;
  5558. result.m[1] = 0.0;
  5559. result.m[3] = 0.0;
  5560. result.m[4] = 0.0;
  5561. result.m[6] = 0.0;
  5562. result.m[7] = 0.0;
  5563. result.m[9] = 0.0;
  5564. result.m[11] = 0.0;
  5565. result.m[12] = 0.0;
  5566. result.m[13] = 0.0;
  5567. result.m[14] = 0.0;
  5568. result._markAsUpdated();
  5569. };
  5570. /**
  5571. * Creates a new rotation matrix for "angle" radians around the Z axis
  5572. * @param angle defines the angle (in radians) to use
  5573. * @return the new matrix
  5574. */
  5575. Matrix.RotationZ = function (angle) {
  5576. var result = new Matrix();
  5577. Matrix.RotationZToRef(angle, result);
  5578. return result;
  5579. };
  5580. /**
  5581. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5582. * @param angle defines the angle (in radians) to use
  5583. * @param result defines the target matrix
  5584. */
  5585. Matrix.RotationZToRef = function (angle, result) {
  5586. var s = Math.sin(angle);
  5587. var c = Math.cos(angle);
  5588. result.m[10] = 1.0;
  5589. result.m[15] = 1.0;
  5590. result.m[0] = c;
  5591. result.m[1] = s;
  5592. result.m[4] = -s;
  5593. result.m[5] = c;
  5594. result.m[2] = 0.0;
  5595. result.m[3] = 0.0;
  5596. result.m[6] = 0.0;
  5597. result.m[7] = 0.0;
  5598. result.m[8] = 0.0;
  5599. result.m[9] = 0.0;
  5600. result.m[11] = 0.0;
  5601. result.m[12] = 0.0;
  5602. result.m[13] = 0.0;
  5603. result.m[14] = 0.0;
  5604. result._markAsUpdated();
  5605. };
  5606. /**
  5607. * Creates a new rotation matrix for "angle" radians around the given axis
  5608. * @param axis defines the axis to use
  5609. * @param angle defines the angle (in radians) to use
  5610. * @return the new matrix
  5611. */
  5612. Matrix.RotationAxis = function (axis, angle) {
  5613. var result = Matrix.Zero();
  5614. Matrix.RotationAxisToRef(axis, angle, result);
  5615. return result;
  5616. };
  5617. /**
  5618. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5619. * @param axis defines the axis to use
  5620. * @param angle defines the angle (in radians) to use
  5621. * @param result defines the target matrix
  5622. */
  5623. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5624. var s = Math.sin(-angle);
  5625. var c = Math.cos(-angle);
  5626. var c1 = 1 - c;
  5627. axis.normalize();
  5628. result.m[0] = (axis.x * axis.x) * c1 + c;
  5629. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5630. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5631. result.m[3] = 0.0;
  5632. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5633. result.m[5] = (axis.y * axis.y) * c1 + c;
  5634. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5635. result.m[7] = 0.0;
  5636. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5637. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5638. result.m[10] = (axis.z * axis.z) * c1 + c;
  5639. result.m[11] = 0.0;
  5640. result.m[15] = 1.0;
  5641. result._markAsUpdated();
  5642. };
  5643. /**
  5644. * Creates a rotation matrix
  5645. * @param yaw defines the yaw angle in radians (Y axis)
  5646. * @param pitch defines the pitch angle in radians (X axis)
  5647. * @param roll defines the roll angle in radians (X axis)
  5648. * @returns the new rotation matrix
  5649. */
  5650. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5651. var result = new Matrix();
  5652. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5653. return result;
  5654. };
  5655. /**
  5656. * Creates a rotation matrix and stores it in a given matrix
  5657. * @param yaw defines the yaw angle in radians (Y axis)
  5658. * @param pitch defines the pitch angle in radians (X axis)
  5659. * @param roll defines the roll angle in radians (X axis)
  5660. * @param result defines the target matrix
  5661. */
  5662. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5663. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5664. this._tempQuaternion.toRotationMatrix(result);
  5665. };
  5666. /**
  5667. * Creates a scaling matrix
  5668. * @param x defines the scale factor on X axis
  5669. * @param y defines the scale factor on Y axis
  5670. * @param z defines the scale factor on Z axis
  5671. * @returns the new matrix
  5672. */
  5673. Matrix.Scaling = function (x, y, z) {
  5674. var result = Matrix.Zero();
  5675. Matrix.ScalingToRef(x, y, z, result);
  5676. return result;
  5677. };
  5678. /**
  5679. * Creates a scaling matrix and stores it in a given matrix
  5680. * @param x defines the scale factor on X axis
  5681. * @param y defines the scale factor on Y axis
  5682. * @param z defines the scale factor on Z axis
  5683. * @param result defines the target matrix
  5684. */
  5685. Matrix.ScalingToRef = function (x, y, z, result) {
  5686. result.m[0] = x;
  5687. result.m[1] = 0.0;
  5688. result.m[2] = 0.0;
  5689. result.m[3] = 0.0;
  5690. result.m[4] = 0.0;
  5691. result.m[5] = y;
  5692. result.m[6] = 0.0;
  5693. result.m[7] = 0.0;
  5694. result.m[8] = 0.0;
  5695. result.m[9] = 0.0;
  5696. result.m[10] = z;
  5697. result.m[11] = 0.0;
  5698. result.m[12] = 0.0;
  5699. result.m[13] = 0.0;
  5700. result.m[14] = 0.0;
  5701. result.m[15] = 1.0;
  5702. result._markAsUpdated();
  5703. };
  5704. /**
  5705. * Creates a translation matrix
  5706. * @param x defines the translation on X axis
  5707. * @param y defines the translation on Y axis
  5708. * @param z defines the translationon Z axis
  5709. * @returns the new matrix
  5710. */
  5711. Matrix.Translation = function (x, y, z) {
  5712. var result = Matrix.Identity();
  5713. Matrix.TranslationToRef(x, y, z, result);
  5714. return result;
  5715. };
  5716. /**
  5717. * Creates a translation matrix and stores it in a given matrix
  5718. * @param x defines the translation on X axis
  5719. * @param y defines the translation on Y axis
  5720. * @param z defines the translationon Z axis
  5721. * @param result defines the target matrix
  5722. */
  5723. Matrix.TranslationToRef = function (x, y, z, result) {
  5724. 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);
  5725. };
  5726. /**
  5727. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5728. * @param startValue defines the start value
  5729. * @param endValue defines the end value
  5730. * @param gradient defines the gradient factor
  5731. * @returns the new matrix
  5732. */
  5733. Matrix.Lerp = function (startValue, endValue, gradient) {
  5734. var result = Matrix.Zero();
  5735. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5736. return result;
  5737. };
  5738. /**
  5739. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5740. * @param startValue defines the start value
  5741. * @param endValue defines the end value
  5742. * @param gradient defines the gradient factor
  5743. * @param result defines the Matrix object where to store data
  5744. */
  5745. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5746. for (var index = 0; index < 16; index++) {
  5747. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5748. }
  5749. result._markAsUpdated();
  5750. };
  5751. /**
  5752. * Builds a new matrix whose values are computed by:
  5753. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5754. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5755. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5756. * @param startValue defines the first matrix
  5757. * @param endValue defines the second matrix
  5758. * @param gradient defines the gradient between the two matrices
  5759. * @returns the new matrix
  5760. */
  5761. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5762. var result = Matrix.Zero();
  5763. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5764. return result;
  5765. };
  5766. /**
  5767. * Update a matrix to values which are computed by:
  5768. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5769. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5770. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5771. * @param startValue defines the first matrix
  5772. * @param endValue defines the second matrix
  5773. * @param gradient defines the gradient between the two matrices
  5774. * @param result defines the target matrix
  5775. */
  5776. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  5777. var startScale = MathTmp.Vector3[0];
  5778. var startRotation = MathTmp.Quaternion[0];
  5779. var startTranslation = MathTmp.Vector3[1];
  5780. startValue.decompose(startScale, startRotation, startTranslation);
  5781. var endScale = MathTmp.Vector3[2];
  5782. var endRotation = MathTmp.Quaternion[1];
  5783. var endTranslation = MathTmp.Vector3[3];
  5784. endValue.decompose(endScale, endRotation, endTranslation);
  5785. var resultScale = MathTmp.Vector3[4];
  5786. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  5787. var resultRotation = MathTmp.Quaternion[2];
  5788. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  5789. var resultTranslation = MathTmp.Vector3[5];
  5790. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  5791. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  5792. };
  5793. /**
  5794. * 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"
  5795. * This function works in left handed mode
  5796. * @param eye defines the final position of the entity
  5797. * @param target defines where the entity should look at
  5798. * @param up defines the up vector for the entity
  5799. * @returns the new matrix
  5800. */
  5801. Matrix.LookAtLH = function (eye, target, up) {
  5802. var result = Matrix.Zero();
  5803. Matrix.LookAtLHToRef(eye, target, up, result);
  5804. return result;
  5805. };
  5806. /**
  5807. * 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".
  5808. * This function works in left handed mode
  5809. * @param eye defines the final position of the entity
  5810. * @param target defines where the entity should look at
  5811. * @param up defines the up vector for the entity
  5812. * @param result defines the target matrix
  5813. */
  5814. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5815. // Z axis
  5816. target.subtractToRef(eye, this._zAxis);
  5817. this._zAxis.normalize();
  5818. // X axis
  5819. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5820. if (this._xAxis.lengthSquared() === 0) {
  5821. this._xAxis.x = 1.0;
  5822. }
  5823. else {
  5824. this._xAxis.normalize();
  5825. }
  5826. // Y axis
  5827. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5828. this._yAxis.normalize();
  5829. // Eye angles
  5830. var ex = -Vector3.Dot(this._xAxis, eye);
  5831. var ey = -Vector3.Dot(this._yAxis, eye);
  5832. var ez = -Vector3.Dot(this._zAxis, eye);
  5833. 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);
  5834. };
  5835. /**
  5836. * 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"
  5837. * This function works in right handed mode
  5838. * @param eye defines the final position of the entity
  5839. * @param target defines where the entity should look at
  5840. * @param up defines the up vector for the entity
  5841. * @returns the new matrix
  5842. */
  5843. Matrix.LookAtRH = function (eye, target, up) {
  5844. var result = Matrix.Zero();
  5845. Matrix.LookAtRHToRef(eye, target, up, result);
  5846. return result;
  5847. };
  5848. /**
  5849. * 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".
  5850. * This function works in right handed mode
  5851. * @param eye defines the final position of the entity
  5852. * @param target defines where the entity should look at
  5853. * @param up defines the up vector for the entity
  5854. * @param result defines the target matrix
  5855. */
  5856. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5857. // Z axis
  5858. eye.subtractToRef(target, this._zAxis);
  5859. this._zAxis.normalize();
  5860. // X axis
  5861. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5862. if (this._xAxis.lengthSquared() === 0) {
  5863. this._xAxis.x = 1.0;
  5864. }
  5865. else {
  5866. this._xAxis.normalize();
  5867. }
  5868. // Y axis
  5869. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5870. this._yAxis.normalize();
  5871. // Eye angles
  5872. var ex = -Vector3.Dot(this._xAxis, eye);
  5873. var ey = -Vector3.Dot(this._yAxis, eye);
  5874. var ez = -Vector3.Dot(this._zAxis, eye);
  5875. 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);
  5876. };
  5877. /**
  5878. * Create a left-handed orthographic projection matrix
  5879. * @param width defines the viewport width
  5880. * @param height defines the viewport height
  5881. * @param znear defines the near clip plane
  5882. * @param zfar defines the far clip plane
  5883. * @returns a new matrix as a left-handed orthographic projection matrix
  5884. */
  5885. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5886. var matrix = Matrix.Zero();
  5887. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5888. return matrix;
  5889. };
  5890. /**
  5891. * Store a left-handed orthographic projection to a given matrix
  5892. * @param width defines the viewport width
  5893. * @param height defines the viewport height
  5894. * @param znear defines the near clip plane
  5895. * @param zfar defines the far clip plane
  5896. * @param result defines the target matrix
  5897. */
  5898. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5899. var n = znear;
  5900. var f = zfar;
  5901. var a = 2.0 / width;
  5902. var b = 2.0 / height;
  5903. var c = 2.0 / (f - n);
  5904. var d = -(f + n) / (f - n);
  5905. 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);
  5906. };
  5907. /**
  5908. * Create a left-handed orthographic projection matrix
  5909. * @param left defines the viewport left coordinate
  5910. * @param right defines the viewport right coordinate
  5911. * @param bottom defines the viewport bottom coordinate
  5912. * @param top defines the viewport top coordinate
  5913. * @param znear defines the near clip plane
  5914. * @param zfar defines the far clip plane
  5915. * @returns a new matrix as a left-handed orthographic projection matrix
  5916. */
  5917. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5918. var matrix = Matrix.Zero();
  5919. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5920. return matrix;
  5921. };
  5922. /**
  5923. * Stores a left-handed orthographic projection into a given matrix
  5924. * @param left defines the viewport left coordinate
  5925. * @param right defines the viewport right coordinate
  5926. * @param bottom defines the viewport bottom coordinate
  5927. * @param top defines the viewport top coordinate
  5928. * @param znear defines the near clip plane
  5929. * @param zfar defines the far clip plane
  5930. * @param result defines the target matrix
  5931. */
  5932. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5933. var n = znear;
  5934. var f = zfar;
  5935. var a = 2.0 / (right - left);
  5936. var b = 2.0 / (top - bottom);
  5937. var c = 2.0 / (f - n);
  5938. var d = -(f + n) / (f - n);
  5939. var i0 = (left + right) / (left - right);
  5940. var i1 = (top + bottom) / (bottom - top);
  5941. 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);
  5942. };
  5943. /**
  5944. * Creates a right-handed orthographic projection matrix
  5945. * @param left defines the viewport left coordinate
  5946. * @param right defines the viewport right coordinate
  5947. * @param bottom defines the viewport bottom coordinate
  5948. * @param top defines the viewport top coordinate
  5949. * @param znear defines the near clip plane
  5950. * @param zfar defines the far clip plane
  5951. * @returns a new matrix as a right-handed orthographic projection matrix
  5952. */
  5953. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5954. var matrix = Matrix.Zero();
  5955. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5956. return matrix;
  5957. };
  5958. /**
  5959. * Stores a right-handed orthographic projection into a given matrix
  5960. * @param left defines the viewport left coordinate
  5961. * @param right defines the viewport right coordinate
  5962. * @param bottom defines the viewport bottom coordinate
  5963. * @param top defines the viewport top coordinate
  5964. * @param znear defines the near clip plane
  5965. * @param zfar defines the far clip plane
  5966. * @param result defines the target matrix
  5967. */
  5968. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5969. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5970. result.m[10] *= -1.0;
  5971. };
  5972. /**
  5973. * Creates a left-handed perspective projection matrix
  5974. * @param width defines the viewport width
  5975. * @param height defines the viewport height
  5976. * @param znear defines the near clip plane
  5977. * @param zfar defines the far clip plane
  5978. * @returns a new matrix as a left-handed perspective projection matrix
  5979. */
  5980. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5981. var matrix = Matrix.Zero();
  5982. var n = znear;
  5983. var f = zfar;
  5984. var a = 2.0 * n / width;
  5985. var b = 2.0 * n / height;
  5986. var c = (f + n) / (f - n);
  5987. var d = -2.0 * f * n / (f - n);
  5988. 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);
  5989. return matrix;
  5990. };
  5991. /**
  5992. * Creates a left-handed perspective projection matrix
  5993. * @param fov defines the horizontal field of view
  5994. * @param aspect defines the aspect ratio
  5995. * @param znear defines the near clip plane
  5996. * @param zfar defines the far clip plane
  5997. * @returns a new matrix as a left-handed perspective projection matrix
  5998. */
  5999. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6000. var matrix = Matrix.Zero();
  6001. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6002. return matrix;
  6003. };
  6004. /**
  6005. * Stores a left-handed perspective projection into a given matrix
  6006. * @param fov defines the horizontal field of view
  6007. * @param aspect defines the aspect ratio
  6008. * @param znear defines the near clip plane
  6009. * @param zfar defines the far clip plane
  6010. * @param result defines the target matrix
  6011. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6012. */
  6013. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6014. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6015. var n = znear;
  6016. var f = zfar;
  6017. var t = 1.0 / (Math.tan(fov * 0.5));
  6018. var a = isVerticalFovFixed ? (t / aspect) : t;
  6019. var b = isVerticalFovFixed ? t : (t * aspect);
  6020. var c = (f + n) / (f - n);
  6021. var d = -2.0 * f * n / (f - n);
  6022. 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);
  6023. };
  6024. /**
  6025. * Creates a right-handed perspective projection matrix
  6026. * @param fov defines the horizontal field of view
  6027. * @param aspect defines the aspect ratio
  6028. * @param znear defines the near clip plane
  6029. * @param zfar defines the far clip plane
  6030. * @returns a new matrix as a right-handed perspective projection matrix
  6031. */
  6032. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6033. var matrix = Matrix.Zero();
  6034. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6035. return matrix;
  6036. };
  6037. /**
  6038. * Stores a right-handed perspective projection into a given matrix
  6039. * @param fov defines the horizontal field of view
  6040. * @param aspect defines the aspect ratio
  6041. * @param znear defines the near clip plane
  6042. * @param zfar defines the far clip plane
  6043. * @param result defines the target matrix
  6044. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6045. */
  6046. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6047. //alternatively this could be expressed as:
  6048. // m = PerspectiveFovLHToRef
  6049. // m[10] *= -1.0;
  6050. // m[11] *= -1.0;
  6051. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6052. var n = znear;
  6053. var f = zfar;
  6054. var t = 1.0 / (Math.tan(fov * 0.5));
  6055. var a = isVerticalFovFixed ? (t / aspect) : t;
  6056. var b = isVerticalFovFixed ? t : (t * aspect);
  6057. var c = -(f + n) / (f - n);
  6058. var d = -2 * f * n / (f - n);
  6059. 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);
  6060. };
  6061. /**
  6062. * Stores a perspective projection for WebVR info a given matrix
  6063. * @param fov defines the field of view
  6064. * @param znear defines the near clip plane
  6065. * @param zfar defines the far clip plane
  6066. * @param result defines the target matrix
  6067. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6068. */
  6069. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6070. if (rightHanded === void 0) { rightHanded = false; }
  6071. var rightHandedFactor = rightHanded ? -1 : 1;
  6072. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6073. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6074. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6075. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6076. var xScale = 2.0 / (leftTan + rightTan);
  6077. var yScale = 2.0 / (upTan + downTan);
  6078. result.m[0] = xScale;
  6079. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6080. result.m[5] = yScale;
  6081. result.m[6] = result.m[7] = 0.0;
  6082. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6083. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6084. result.m[10] = -zfar / (znear - zfar);
  6085. result.m[11] = 1.0 * rightHandedFactor;
  6086. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6087. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6088. result._markAsUpdated();
  6089. };
  6090. /**
  6091. * Computes a complete transformation matrix
  6092. * @param viewport defines the viewport to use
  6093. * @param world defines the world matrix
  6094. * @param view defines the view matrix
  6095. * @param projection defines the projection matrix
  6096. * @param zmin defines the near clip plane
  6097. * @param zmax defines the far clip plane
  6098. * @returns the transformation matrix
  6099. */
  6100. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6101. var cw = viewport.width;
  6102. var ch = viewport.height;
  6103. var cx = viewport.x;
  6104. var cy = viewport.y;
  6105. 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);
  6106. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6107. };
  6108. /**
  6109. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6110. * @param matrix defines the matrix to use
  6111. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed matrix
  6112. */
  6113. Matrix.GetAsMatrix2x2 = function (matrix) {
  6114. return new Float32Array([
  6115. matrix.m[0], matrix.m[1],
  6116. matrix.m[4], matrix.m[5]
  6117. ]);
  6118. };
  6119. /**
  6120. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6121. * @param matrix defines the matrix to use
  6122. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed matrix
  6123. */
  6124. Matrix.GetAsMatrix3x3 = function (matrix) {
  6125. return new Float32Array([
  6126. matrix.m[0], matrix.m[1], matrix.m[2],
  6127. matrix.m[4], matrix.m[5], matrix.m[6],
  6128. matrix.m[8], matrix.m[9], matrix.m[10]
  6129. ]);
  6130. };
  6131. /**
  6132. * Compute the transpose of a given matrix
  6133. * @param matrix defines the matrix to transpose
  6134. * @returns the new matrix
  6135. */
  6136. Matrix.Transpose = function (matrix) {
  6137. var result = new Matrix();
  6138. Matrix.TransposeToRef(matrix, result);
  6139. return result;
  6140. };
  6141. /**
  6142. * Compute the transpose of a matrix and store it in a target matrix
  6143. * @param matrix defines the matrix to transpose
  6144. * @param result defines the target matrix
  6145. */
  6146. Matrix.TransposeToRef = function (matrix, result) {
  6147. result.m[0] = matrix.m[0];
  6148. result.m[1] = matrix.m[4];
  6149. result.m[2] = matrix.m[8];
  6150. result.m[3] = matrix.m[12];
  6151. result.m[4] = matrix.m[1];
  6152. result.m[5] = matrix.m[5];
  6153. result.m[6] = matrix.m[9];
  6154. result.m[7] = matrix.m[13];
  6155. result.m[8] = matrix.m[2];
  6156. result.m[9] = matrix.m[6];
  6157. result.m[10] = matrix.m[10];
  6158. result.m[11] = matrix.m[14];
  6159. result.m[12] = matrix.m[3];
  6160. result.m[13] = matrix.m[7];
  6161. result.m[14] = matrix.m[11];
  6162. result.m[15] = matrix.m[15];
  6163. };
  6164. /**
  6165. * Computes a reflection matrix from a plane
  6166. * @param plane defines the reflection plane
  6167. * @returns a new matrix
  6168. */
  6169. Matrix.Reflection = function (plane) {
  6170. var matrix = new Matrix();
  6171. Matrix.ReflectionToRef(plane, matrix);
  6172. return matrix;
  6173. };
  6174. /**
  6175. * Computes a reflection matrix from a plane
  6176. * @param plane defines the reflection plane
  6177. * @param result defines the target matrix
  6178. */
  6179. Matrix.ReflectionToRef = function (plane, result) {
  6180. plane.normalize();
  6181. var x = plane.normal.x;
  6182. var y = plane.normal.y;
  6183. var z = plane.normal.z;
  6184. var temp = -2 * x;
  6185. var temp2 = -2 * y;
  6186. var temp3 = -2 * z;
  6187. result.m[0] = (temp * x) + 1;
  6188. result.m[1] = temp2 * x;
  6189. result.m[2] = temp3 * x;
  6190. result.m[3] = 0.0;
  6191. result.m[4] = temp * y;
  6192. result.m[5] = (temp2 * y) + 1;
  6193. result.m[6] = temp3 * y;
  6194. result.m[7] = 0.0;
  6195. result.m[8] = temp * z;
  6196. result.m[9] = temp2 * z;
  6197. result.m[10] = (temp3 * z) + 1;
  6198. result.m[11] = 0.0;
  6199. result.m[12] = temp * plane.d;
  6200. result.m[13] = temp2 * plane.d;
  6201. result.m[14] = temp3 * plane.d;
  6202. result.m[15] = 1.0;
  6203. result._markAsUpdated();
  6204. };
  6205. /**
  6206. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6207. * @param xaxis defines the value of the 1st axis
  6208. * @param yaxis defines the value of the 2nd axis
  6209. * @param zaxis defines the value of the 3rd axis
  6210. * @param result defines the target matrix
  6211. */
  6212. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6213. result.m[0] = xaxis.x;
  6214. result.m[1] = xaxis.y;
  6215. result.m[2] = xaxis.z;
  6216. result.m[3] = 0.0;
  6217. result.m[4] = yaxis.x;
  6218. result.m[5] = yaxis.y;
  6219. result.m[6] = yaxis.z;
  6220. result.m[7] = 0.0;
  6221. result.m[8] = zaxis.x;
  6222. result.m[9] = zaxis.y;
  6223. result.m[10] = zaxis.z;
  6224. result.m[11] = 0.0;
  6225. result.m[12] = 0.0;
  6226. result.m[13] = 0.0;
  6227. result.m[14] = 0.0;
  6228. result.m[15] = 1.0;
  6229. result._markAsUpdated();
  6230. };
  6231. /**
  6232. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6233. * @param quat defines the quaternion to use
  6234. * @param result defines the target matrix
  6235. */
  6236. Matrix.FromQuaternionToRef = function (quat, result) {
  6237. var xx = quat.x * quat.x;
  6238. var yy = quat.y * quat.y;
  6239. var zz = quat.z * quat.z;
  6240. var xy = quat.x * quat.y;
  6241. var zw = quat.z * quat.w;
  6242. var zx = quat.z * quat.x;
  6243. var yw = quat.y * quat.w;
  6244. var yz = quat.y * quat.z;
  6245. var xw = quat.x * quat.w;
  6246. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6247. result.m[1] = 2.0 * (xy + zw);
  6248. result.m[2] = 2.0 * (zx - yw);
  6249. result.m[3] = 0.0;
  6250. result.m[4] = 2.0 * (xy - zw);
  6251. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6252. result.m[6] = 2.0 * (yz + xw);
  6253. result.m[7] = 0.0;
  6254. result.m[8] = 2.0 * (zx + yw);
  6255. result.m[9] = 2.0 * (yz - xw);
  6256. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6257. result.m[11] = 0.0;
  6258. result.m[12] = 0.0;
  6259. result.m[13] = 0.0;
  6260. result.m[14] = 0.0;
  6261. result.m[15] = 1.0;
  6262. result._markAsUpdated();
  6263. };
  6264. Matrix._tempQuaternion = new Quaternion();
  6265. Matrix._xAxis = Vector3.Zero();
  6266. Matrix._yAxis = Vector3.Zero();
  6267. Matrix._zAxis = Vector3.Zero();
  6268. Matrix._updateFlagSeed = 0;
  6269. Matrix._identityReadOnly = Matrix.Identity();
  6270. return Matrix;
  6271. }());
  6272. BABYLON.Matrix = Matrix;
  6273. var Plane = /** @class */ (function () {
  6274. /**
  6275. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6276. */
  6277. function Plane(a, b, c, d) {
  6278. this.normal = new Vector3(a, b, c);
  6279. this.d = d;
  6280. }
  6281. /**
  6282. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6283. */
  6284. Plane.prototype.asArray = function () {
  6285. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6286. };
  6287. // Methods
  6288. /**
  6289. * Returns a new plane copied from the current Plane.
  6290. */
  6291. Plane.prototype.clone = function () {
  6292. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6293. };
  6294. /**
  6295. * Returns the string "Plane".
  6296. */
  6297. Plane.prototype.getClassName = function () {
  6298. return "Plane";
  6299. };
  6300. /**
  6301. * Returns the Plane hash code.
  6302. */
  6303. Plane.prototype.getHashCode = function () {
  6304. var hash = this.normal.getHashCode();
  6305. hash = (hash * 397) ^ (this.d || 0);
  6306. return hash;
  6307. };
  6308. /**
  6309. * Normalize the current Plane in place.
  6310. * Returns the updated Plane.
  6311. */
  6312. Plane.prototype.normalize = function () {
  6313. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6314. var magnitude = 0.0;
  6315. if (norm !== 0) {
  6316. magnitude = 1.0 / norm;
  6317. }
  6318. this.normal.x *= magnitude;
  6319. this.normal.y *= magnitude;
  6320. this.normal.z *= magnitude;
  6321. this.d *= magnitude;
  6322. return this;
  6323. };
  6324. /**
  6325. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6326. */
  6327. Plane.prototype.transform = function (transformation) {
  6328. var transposedMatrix = Matrix.Transpose(transformation);
  6329. var x = this.normal.x;
  6330. var y = this.normal.y;
  6331. var z = this.normal.z;
  6332. var d = this.d;
  6333. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6334. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6335. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6336. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6337. return new Plane(normalX, normalY, normalZ, finalD);
  6338. };
  6339. /**
  6340. * Returns the dot product (float) of the point coordinates and the plane normal.
  6341. */
  6342. Plane.prototype.dotCoordinate = function (point) {
  6343. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6344. };
  6345. /**
  6346. * Updates the current Plane from the plane defined by the three passed points.
  6347. * Returns the updated Plane.
  6348. */
  6349. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6350. var x1 = point2.x - point1.x;
  6351. var y1 = point2.y - point1.y;
  6352. var z1 = point2.z - point1.z;
  6353. var x2 = point3.x - point1.x;
  6354. var y2 = point3.y - point1.y;
  6355. var z2 = point3.z - point1.z;
  6356. var yz = (y1 * z2) - (z1 * y2);
  6357. var xz = (z1 * x2) - (x1 * z2);
  6358. var xy = (x1 * y2) - (y1 * x2);
  6359. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6360. var invPyth;
  6361. if (pyth !== 0) {
  6362. invPyth = 1.0 / pyth;
  6363. }
  6364. else {
  6365. invPyth = 0.0;
  6366. }
  6367. this.normal.x = yz * invPyth;
  6368. this.normal.y = xz * invPyth;
  6369. this.normal.z = xy * invPyth;
  6370. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6371. return this;
  6372. };
  6373. /**
  6374. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6375. */
  6376. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6377. var dot = Vector3.Dot(this.normal, direction);
  6378. return (dot <= epsilon);
  6379. };
  6380. /**
  6381. * Returns the signed distance (float) from the passed point to the Plane.
  6382. */
  6383. Plane.prototype.signedDistanceTo = function (point) {
  6384. return Vector3.Dot(point, this.normal) + this.d;
  6385. };
  6386. // Statics
  6387. /**
  6388. * Returns a new Plane from the passed array.
  6389. */
  6390. Plane.FromArray = function (array) {
  6391. return new Plane(array[0], array[1], array[2], array[3]);
  6392. };
  6393. /**
  6394. * Returns a new Plane defined by the three passed points.
  6395. */
  6396. Plane.FromPoints = function (point1, point2, point3) {
  6397. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6398. result.copyFromPoints(point1, point2, point3);
  6399. return result;
  6400. };
  6401. /**
  6402. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6403. * Note : the vector "normal" is updated because normalized.
  6404. */
  6405. Plane.FromPositionAndNormal = function (origin, normal) {
  6406. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6407. normal.normalize();
  6408. result.normal = normal;
  6409. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6410. return result;
  6411. };
  6412. /**
  6413. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6414. */
  6415. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6416. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6417. return Vector3.Dot(point, normal) + d;
  6418. };
  6419. return Plane;
  6420. }());
  6421. BABYLON.Plane = Plane;
  6422. var Viewport = /** @class */ (function () {
  6423. /**
  6424. * Creates a Viewport object located at (x, y) and sized (width, height).
  6425. */
  6426. function Viewport(x, y, width, height) {
  6427. this.x = x;
  6428. this.y = y;
  6429. this.width = width;
  6430. this.height = height;
  6431. }
  6432. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6433. if (renderWidthOrEngine.getRenderWidth) {
  6434. var engine = renderWidthOrEngine;
  6435. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6436. }
  6437. var renderWidth = renderWidthOrEngine;
  6438. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6439. };
  6440. /**
  6441. * Returns a new Viewport copied from the current one.
  6442. */
  6443. Viewport.prototype.clone = function () {
  6444. return new Viewport(this.x, this.y, this.width, this.height);
  6445. };
  6446. return Viewport;
  6447. }());
  6448. BABYLON.Viewport = Viewport;
  6449. var Frustum = /** @class */ (function () {
  6450. function Frustum() {
  6451. }
  6452. /**
  6453. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6454. */
  6455. Frustum.GetPlanes = function (transform) {
  6456. var frustumPlanes = [];
  6457. for (var index = 0; index < 6; index++) {
  6458. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6459. }
  6460. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6461. return frustumPlanes;
  6462. };
  6463. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6464. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6465. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6466. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6467. frustumPlane.d = transform.m[15] + transform.m[14];
  6468. frustumPlane.normalize();
  6469. };
  6470. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6471. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6472. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6473. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6474. frustumPlane.d = transform.m[15] - transform.m[14];
  6475. frustumPlane.normalize();
  6476. };
  6477. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6478. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6479. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6480. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6481. frustumPlane.d = transform.m[15] + transform.m[12];
  6482. frustumPlane.normalize();
  6483. };
  6484. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6485. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6486. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6487. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6488. frustumPlane.d = transform.m[15] - transform.m[12];
  6489. frustumPlane.normalize();
  6490. };
  6491. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6492. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6493. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6494. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6495. frustumPlane.d = transform.m[15] - transform.m[13];
  6496. frustumPlane.normalize();
  6497. };
  6498. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6499. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6500. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6501. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6502. frustumPlane.d = transform.m[15] + transform.m[13];
  6503. frustumPlane.normalize();
  6504. };
  6505. /**
  6506. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6507. */
  6508. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6509. // Near
  6510. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6511. // Far
  6512. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6513. // Left
  6514. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6515. // Right
  6516. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6517. // Top
  6518. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6519. // Bottom
  6520. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6521. };
  6522. return Frustum;
  6523. }());
  6524. BABYLON.Frustum = Frustum;
  6525. var Space;
  6526. (function (Space) {
  6527. Space[Space["LOCAL"] = 0] = "LOCAL";
  6528. Space[Space["WORLD"] = 1] = "WORLD";
  6529. Space[Space["BONE"] = 2] = "BONE";
  6530. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6531. var Axis = /** @class */ (function () {
  6532. function Axis() {
  6533. }
  6534. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6535. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6536. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6537. return Axis;
  6538. }());
  6539. BABYLON.Axis = Axis;
  6540. ;
  6541. var BezierCurve = /** @class */ (function () {
  6542. function BezierCurve() {
  6543. }
  6544. /**
  6545. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6546. */
  6547. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6548. // Extract X (which is equal to time here)
  6549. var f0 = 1 - 3 * x2 + 3 * x1;
  6550. var f1 = 3 * x2 - 6 * x1;
  6551. var f2 = 3 * x1;
  6552. var refinedT = t;
  6553. for (var i = 0; i < 5; i++) {
  6554. var refinedT2 = refinedT * refinedT;
  6555. var refinedT3 = refinedT2 * refinedT;
  6556. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6557. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6558. refinedT -= (x - t) * slope;
  6559. refinedT = Math.min(1, Math.max(0, refinedT));
  6560. }
  6561. // Resolve cubic bezier for the given x
  6562. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6563. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6564. Math.pow(refinedT, 3);
  6565. };
  6566. return BezierCurve;
  6567. }());
  6568. BABYLON.BezierCurve = BezierCurve;
  6569. var Orientation;
  6570. (function (Orientation) {
  6571. Orientation[Orientation["CW"] = 0] = "CW";
  6572. Orientation[Orientation["CCW"] = 1] = "CCW";
  6573. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6574. var Angle = /** @class */ (function () {
  6575. /**
  6576. * Creates an Angle object of "radians" radians (float).
  6577. */
  6578. function Angle(radians) {
  6579. var _this = this;
  6580. /**
  6581. * Returns the Angle value in degrees (float).
  6582. */
  6583. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6584. /**
  6585. * Returns the Angle value in radians (float).
  6586. */
  6587. this.radians = function () { return _this._radians; };
  6588. this._radians = radians;
  6589. if (this._radians < 0.0)
  6590. this._radians += (2.0 * Math.PI);
  6591. }
  6592. /**
  6593. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6594. */
  6595. Angle.BetweenTwoPoints = function (a, b) {
  6596. var delta = b.subtract(a);
  6597. var theta = Math.atan2(delta.y, delta.x);
  6598. return new Angle(theta);
  6599. };
  6600. /**
  6601. * Returns a new Angle object from the passed float in radians.
  6602. */
  6603. Angle.FromRadians = function (radians) {
  6604. return new Angle(radians);
  6605. };
  6606. /**
  6607. * Returns a new Angle object from the passed float in degrees.
  6608. */
  6609. Angle.FromDegrees = function (degrees) {
  6610. return new Angle(degrees * Math.PI / 180.0);
  6611. };
  6612. return Angle;
  6613. }());
  6614. BABYLON.Angle = Angle;
  6615. var Arc2 = /** @class */ (function () {
  6616. /**
  6617. * Creates an Arc object from the three passed points : start, middle and end.
  6618. */
  6619. function Arc2(startPoint, midPoint, endPoint) {
  6620. this.startPoint = startPoint;
  6621. this.midPoint = midPoint;
  6622. this.endPoint = endPoint;
  6623. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6624. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6625. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6626. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6627. 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);
  6628. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6629. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6630. var a1 = this.startAngle.degrees();
  6631. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6632. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6633. // angles correction
  6634. if (a2 - a1 > +180.0)
  6635. a2 -= 360.0;
  6636. if (a2 - a1 < -180.0)
  6637. a2 += 360.0;
  6638. if (a3 - a2 > +180.0)
  6639. a3 -= 360.0;
  6640. if (a3 - a2 < -180.0)
  6641. a3 += 360.0;
  6642. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6643. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6644. }
  6645. return Arc2;
  6646. }());
  6647. BABYLON.Arc2 = Arc2;
  6648. var Path2 = /** @class */ (function () {
  6649. /**
  6650. * Creates a Path2 object from the starting 2D coordinates x and y.
  6651. */
  6652. function Path2(x, y) {
  6653. this._points = new Array();
  6654. this._length = 0.0;
  6655. this.closed = false;
  6656. this._points.push(new Vector2(x, y));
  6657. }
  6658. /**
  6659. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6660. * Returns the updated Path2.
  6661. */
  6662. Path2.prototype.addLineTo = function (x, y) {
  6663. if (this.closed) {
  6664. return this;
  6665. }
  6666. var newPoint = new Vector2(x, y);
  6667. var previousPoint = this._points[this._points.length - 1];
  6668. this._points.push(newPoint);
  6669. this._length += newPoint.subtract(previousPoint).length();
  6670. return this;
  6671. };
  6672. /**
  6673. * 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.
  6674. * Returns the updated Path2.
  6675. */
  6676. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6677. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6678. if (this.closed) {
  6679. return this;
  6680. }
  6681. var startPoint = this._points[this._points.length - 1];
  6682. var midPoint = new Vector2(midX, midY);
  6683. var endPoint = new Vector2(endX, endY);
  6684. var arc = new Arc2(startPoint, midPoint, endPoint);
  6685. var increment = arc.angle.radians() / numberOfSegments;
  6686. if (arc.orientation === Orientation.CW)
  6687. increment *= -1;
  6688. var currentAngle = arc.startAngle.radians() + increment;
  6689. for (var i = 0; i < numberOfSegments; i++) {
  6690. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6691. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6692. this.addLineTo(x, y);
  6693. currentAngle += increment;
  6694. }
  6695. return this;
  6696. };
  6697. /**
  6698. * Closes the Path2.
  6699. * Returns the Path2.
  6700. */
  6701. Path2.prototype.close = function () {
  6702. this.closed = true;
  6703. return this;
  6704. };
  6705. /**
  6706. * Returns the Path2 total length (float).
  6707. */
  6708. Path2.prototype.length = function () {
  6709. var result = this._length;
  6710. if (!this.closed) {
  6711. var lastPoint = this._points[this._points.length - 1];
  6712. var firstPoint = this._points[0];
  6713. result += (firstPoint.subtract(lastPoint).length());
  6714. }
  6715. return result;
  6716. };
  6717. /**
  6718. * Returns the Path2 internal array of points.
  6719. */
  6720. Path2.prototype.getPoints = function () {
  6721. return this._points;
  6722. };
  6723. /**
  6724. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6725. */
  6726. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6727. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6728. return Vector2.Zero();
  6729. }
  6730. var lengthPosition = normalizedLengthPosition * this.length();
  6731. var previousOffset = 0;
  6732. for (var i = 0; i < this._points.length; i++) {
  6733. var j = (i + 1) % this._points.length;
  6734. var a = this._points[i];
  6735. var b = this._points[j];
  6736. var bToA = b.subtract(a);
  6737. var nextOffset = (bToA.length() + previousOffset);
  6738. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6739. var dir = bToA.normalize();
  6740. var localOffset = lengthPosition - previousOffset;
  6741. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6742. }
  6743. previousOffset = nextOffset;
  6744. }
  6745. return Vector2.Zero();
  6746. };
  6747. /**
  6748. * Returns a new Path2 starting at the coordinates (x, y).
  6749. */
  6750. Path2.StartingAt = function (x, y) {
  6751. return new Path2(x, y);
  6752. };
  6753. return Path2;
  6754. }());
  6755. BABYLON.Path2 = Path2;
  6756. var Path3D = /** @class */ (function () {
  6757. /**
  6758. * new Path3D(path, normal, raw)
  6759. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6760. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6761. * path : an array of Vector3, the curve axis of the Path3D
  6762. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6763. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6764. */
  6765. function Path3D(path, firstNormal, raw) {
  6766. if (firstNormal === void 0) { firstNormal = null; }
  6767. this.path = path;
  6768. this._curve = new Array();
  6769. this._distances = new Array();
  6770. this._tangents = new Array();
  6771. this._normals = new Array();
  6772. this._binormals = new Array();
  6773. for (var p = 0; p < path.length; p++) {
  6774. this._curve[p] = path[p].clone(); // hard copy
  6775. }
  6776. this._raw = raw || false;
  6777. this._compute(firstNormal);
  6778. }
  6779. /**
  6780. * Returns the Path3D array of successive Vector3 designing its curve.
  6781. */
  6782. Path3D.prototype.getCurve = function () {
  6783. return this._curve;
  6784. };
  6785. /**
  6786. * Returns an array populated with tangent vectors on each Path3D curve point.
  6787. */
  6788. Path3D.prototype.getTangents = function () {
  6789. return this._tangents;
  6790. };
  6791. /**
  6792. * Returns an array populated with normal vectors on each Path3D curve point.
  6793. */
  6794. Path3D.prototype.getNormals = function () {
  6795. return this._normals;
  6796. };
  6797. /**
  6798. * Returns an array populated with binormal vectors on each Path3D curve point.
  6799. */
  6800. Path3D.prototype.getBinormals = function () {
  6801. return this._binormals;
  6802. };
  6803. /**
  6804. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6805. */
  6806. Path3D.prototype.getDistances = function () {
  6807. return this._distances;
  6808. };
  6809. /**
  6810. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6811. * Returns the same object updated.
  6812. */
  6813. Path3D.prototype.update = function (path, firstNormal) {
  6814. if (firstNormal === void 0) { firstNormal = null; }
  6815. for (var p = 0; p < path.length; p++) {
  6816. this._curve[p].x = path[p].x;
  6817. this._curve[p].y = path[p].y;
  6818. this._curve[p].z = path[p].z;
  6819. }
  6820. this._compute(firstNormal);
  6821. return this;
  6822. };
  6823. // private function compute() : computes tangents, normals and binormals
  6824. Path3D.prototype._compute = function (firstNormal) {
  6825. var l = this._curve.length;
  6826. // first and last tangents
  6827. this._tangents[0] = this._getFirstNonNullVector(0);
  6828. if (!this._raw) {
  6829. this._tangents[0].normalize();
  6830. }
  6831. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6832. if (!this._raw) {
  6833. this._tangents[l - 1].normalize();
  6834. }
  6835. // normals and binormals at first point : arbitrary vector with _normalVector()
  6836. var tg0 = this._tangents[0];
  6837. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6838. this._normals[0] = pp0;
  6839. if (!this._raw) {
  6840. this._normals[0].normalize();
  6841. }
  6842. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6843. if (!this._raw) {
  6844. this._binormals[0].normalize();
  6845. }
  6846. this._distances[0] = 0.0;
  6847. // normals and binormals : next points
  6848. var prev; // previous vector (segment)
  6849. var cur; // current vector (segment)
  6850. var curTang; // current tangent
  6851. // previous normal
  6852. var prevBinor; // previous binormal
  6853. for (var i = 1; i < l; i++) {
  6854. // tangents
  6855. prev = this._getLastNonNullVector(i);
  6856. if (i < l - 1) {
  6857. cur = this._getFirstNonNullVector(i);
  6858. this._tangents[i] = prev.add(cur);
  6859. this._tangents[i].normalize();
  6860. }
  6861. this._distances[i] = this._distances[i - 1] + prev.length();
  6862. // normals and binormals
  6863. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6864. curTang = this._tangents[i];
  6865. prevBinor = this._binormals[i - 1];
  6866. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6867. if (!this._raw) {
  6868. this._normals[i].normalize();
  6869. }
  6870. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6871. if (!this._raw) {
  6872. this._binormals[i].normalize();
  6873. }
  6874. }
  6875. };
  6876. // private function getFirstNonNullVector(index)
  6877. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6878. Path3D.prototype._getFirstNonNullVector = function (index) {
  6879. var i = 1;
  6880. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6881. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6882. i++;
  6883. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6884. }
  6885. return nNVector;
  6886. };
  6887. // private function getLastNonNullVector(index)
  6888. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6889. Path3D.prototype._getLastNonNullVector = function (index) {
  6890. var i = 1;
  6891. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6892. while (nLVector.length() === 0 && index > i + 1) {
  6893. i++;
  6894. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6895. }
  6896. return nLVector;
  6897. };
  6898. // private function normalVector(v0, vt, va) :
  6899. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6900. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6901. Path3D.prototype._normalVector = function (v0, vt, va) {
  6902. var normal0;
  6903. var tgl = vt.length();
  6904. if (tgl === 0.0) {
  6905. tgl = 1.0;
  6906. }
  6907. if (va === undefined || va === null) {
  6908. var point;
  6909. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6910. point = new Vector3(0.0, -1.0, 0.0);
  6911. }
  6912. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6913. point = new Vector3(1.0, 0.0, 0.0);
  6914. }
  6915. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6916. point = new Vector3(0.0, 0.0, 1.0);
  6917. }
  6918. else {
  6919. point = Vector3.Zero();
  6920. }
  6921. normal0 = Vector3.Cross(vt, point);
  6922. }
  6923. else {
  6924. normal0 = Vector3.Cross(vt, va);
  6925. Vector3.CrossToRef(normal0, vt, normal0);
  6926. }
  6927. normal0.normalize();
  6928. return normal0;
  6929. };
  6930. return Path3D;
  6931. }());
  6932. BABYLON.Path3D = Path3D;
  6933. var Curve3 = /** @class */ (function () {
  6934. /**
  6935. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6936. * A Curve3 is designed from a series of successive Vector3.
  6937. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6938. */
  6939. function Curve3(points) {
  6940. this._length = 0.0;
  6941. this._points = points;
  6942. this._length = this._computeLength(points);
  6943. }
  6944. /**
  6945. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6946. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6947. * @param v1 (Vector3) the control point
  6948. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6949. * @param nbPoints (integer) the wanted number of points in the curve
  6950. */
  6951. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6952. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6953. var bez = new Array();
  6954. var equation = function (t, val0, val1, val2) {
  6955. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6956. return res;
  6957. };
  6958. for (var i = 0; i <= nbPoints; i++) {
  6959. 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)));
  6960. }
  6961. return new Curve3(bez);
  6962. };
  6963. /**
  6964. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6965. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6966. * @param v1 (Vector3) the first control point
  6967. * @param v2 (Vector3) the second control point
  6968. * @param v3 (Vector3) the end point of the Cubic Bezier
  6969. * @param nbPoints (integer) the wanted number of points in the curve
  6970. */
  6971. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6972. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6973. var bez = new Array();
  6974. var equation = function (t, val0, val1, val2, val3) {
  6975. 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;
  6976. return res;
  6977. };
  6978. for (var i = 0; i <= nbPoints; i++) {
  6979. 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)));
  6980. }
  6981. return new Curve3(bez);
  6982. };
  6983. /**
  6984. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6985. * @param p1 (Vector3) the origin point of the Hermite Spline
  6986. * @param t1 (Vector3) the tangent vector at the origin point
  6987. * @param p2 (Vector3) the end point of the Hermite Spline
  6988. * @param t2 (Vector3) the tangent vector at the end point
  6989. * @param nbPoints (integer) the wanted number of points in the curve
  6990. */
  6991. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6992. var hermite = new Array();
  6993. var step = 1.0 / nbPoints;
  6994. for (var i = 0; i <= nbPoints; i++) {
  6995. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6996. }
  6997. return new Curve3(hermite);
  6998. };
  6999. /**
  7000. * Returns a Curve3 object along a CatmullRom Spline curve :
  7001. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7002. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7003. */
  7004. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7005. var totalPoints = new Array();
  7006. totalPoints.push(points[0].clone());
  7007. Array.prototype.push.apply(totalPoints, points);
  7008. totalPoints.push(points[points.length - 1].clone());
  7009. var catmullRom = new Array();
  7010. var step = 1.0 / nbPoints;
  7011. var amount = 0.0;
  7012. for (var i = 0; i < totalPoints.length - 3; i++) {
  7013. amount = 0;
  7014. for (var c = 0; c < nbPoints; c++) {
  7015. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7016. amount += step;
  7017. }
  7018. }
  7019. i--;
  7020. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7021. return new Curve3(catmullRom);
  7022. };
  7023. /**
  7024. * Returns the Curve3 stored array of successive Vector3
  7025. */
  7026. Curve3.prototype.getPoints = function () {
  7027. return this._points;
  7028. };
  7029. /**
  7030. * Returns the computed length (float) of the curve.
  7031. */
  7032. Curve3.prototype.length = function () {
  7033. return this._length;
  7034. };
  7035. /**
  7036. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7037. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7038. * curveA and curveB keep unchanged.
  7039. */
  7040. Curve3.prototype.continue = function (curve) {
  7041. var lastPoint = this._points[this._points.length - 1];
  7042. var continuedPoints = this._points.slice();
  7043. var curvePoints = curve.getPoints();
  7044. for (var i = 1; i < curvePoints.length; i++) {
  7045. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7046. }
  7047. var continuedCurve = new Curve3(continuedPoints);
  7048. return continuedCurve;
  7049. };
  7050. Curve3.prototype._computeLength = function (path) {
  7051. var l = 0;
  7052. for (var i = 1; i < path.length; i++) {
  7053. l += (path[i].subtract(path[i - 1])).length();
  7054. }
  7055. return l;
  7056. };
  7057. return Curve3;
  7058. }());
  7059. BABYLON.Curve3 = Curve3;
  7060. // Vertex formats
  7061. var PositionNormalVertex = /** @class */ (function () {
  7062. function PositionNormalVertex(position, normal) {
  7063. if (position === void 0) { position = Vector3.Zero(); }
  7064. if (normal === void 0) { normal = Vector3.Up(); }
  7065. this.position = position;
  7066. this.normal = normal;
  7067. }
  7068. PositionNormalVertex.prototype.clone = function () {
  7069. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7070. };
  7071. return PositionNormalVertex;
  7072. }());
  7073. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7074. var PositionNormalTextureVertex = /** @class */ (function () {
  7075. function PositionNormalTextureVertex(position, normal, uv) {
  7076. if (position === void 0) { position = Vector3.Zero(); }
  7077. if (normal === void 0) { normal = Vector3.Up(); }
  7078. if (uv === void 0) { uv = Vector2.Zero(); }
  7079. this.position = position;
  7080. this.normal = normal;
  7081. this.uv = uv;
  7082. }
  7083. PositionNormalTextureVertex.prototype.clone = function () {
  7084. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7085. };
  7086. return PositionNormalTextureVertex;
  7087. }());
  7088. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7089. // Temporary pre-allocated objects for engine internal use
  7090. // usage in any internal function :
  7091. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7092. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7093. var Tmp = /** @class */ (function () {
  7094. function Tmp() {
  7095. }
  7096. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7097. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7098. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7099. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7100. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7101. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7102. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7103. Matrix.Zero(), Matrix.Zero(),
  7104. Matrix.Zero(), Matrix.Zero(),
  7105. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7106. return Tmp;
  7107. }());
  7108. BABYLON.Tmp = Tmp;
  7109. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  7110. var MathTmp = /** @class */ (function () {
  7111. function MathTmp() {
  7112. }
  7113. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7114. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7115. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7116. return MathTmp;
  7117. }());
  7118. })(BABYLON || (BABYLON = {}));
  7119. //# sourceMappingURL=babylon.math.js.map
  7120. "use strict";
  7121. var BABYLON;
  7122. (function (BABYLON) {
  7123. var Scalar = /** @class */ (function () {
  7124. function Scalar() {
  7125. }
  7126. /**
  7127. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7128. */
  7129. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7130. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7131. var num = a - b;
  7132. return -epsilon <= num && num <= epsilon;
  7133. };
  7134. /**
  7135. * Returns a string : the upper case translation of the number i to hexadecimal.
  7136. */
  7137. Scalar.ToHex = function (i) {
  7138. var str = i.toString(16);
  7139. if (i <= 15) {
  7140. return ("0" + str).toUpperCase();
  7141. }
  7142. return str.toUpperCase();
  7143. };
  7144. /**
  7145. * Returns -1 if value is negative and +1 is value is positive.
  7146. * Returns the value itself if it's equal to zero.
  7147. */
  7148. Scalar.Sign = function (value) {
  7149. value = +value; // convert to a number
  7150. if (value === 0 || isNaN(value))
  7151. return value;
  7152. return value > 0 ? 1 : -1;
  7153. };
  7154. /**
  7155. * Returns the value itself if it's between min and max.
  7156. * Returns min if the value is lower than min.
  7157. * Returns max if the value is greater than max.
  7158. */
  7159. Scalar.Clamp = function (value, min, max) {
  7160. if (min === void 0) { min = 0; }
  7161. if (max === void 0) { max = 1; }
  7162. return Math.min(max, Math.max(min, value));
  7163. };
  7164. /**
  7165. * Returns the log2 of value.
  7166. */
  7167. Scalar.Log2 = function (value) {
  7168. return Math.log(value) * Math.LOG2E;
  7169. };
  7170. /**
  7171. * Loops the value, so that it is never larger than length and never smaller than 0.
  7172. *
  7173. * This is similar to the modulo operator but it works with floating point numbers.
  7174. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7175. * With t = 5 and length = 2.5, the result would be 0.0.
  7176. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7177. */
  7178. Scalar.Repeat = function (value, length) {
  7179. return value - Math.floor(value / length) * length;
  7180. };
  7181. /**
  7182. * Normalize the value between 0.0 and 1.0 using min and max values
  7183. */
  7184. Scalar.Normalize = function (value, min, max) {
  7185. return (value - min) / (max - min);
  7186. };
  7187. /**
  7188. * Denormalize the value from 0.0 and 1.0 using min and max values
  7189. */
  7190. Scalar.Denormalize = function (normalized, min, max) {
  7191. return (normalized * (max - min) + min);
  7192. };
  7193. /**
  7194. * Calculates the shortest difference between two given angles given in degrees.
  7195. */
  7196. Scalar.DeltaAngle = function (current, target) {
  7197. var num = Scalar.Repeat(target - current, 360.0);
  7198. if (num > 180.0) {
  7199. num -= 360.0;
  7200. }
  7201. return num;
  7202. };
  7203. /**
  7204. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7205. *
  7206. * The returned value will move back and forth between 0 and length
  7207. */
  7208. Scalar.PingPong = function (tx, length) {
  7209. var t = Scalar.Repeat(tx, length * 2.0);
  7210. return length - Math.abs(t - length);
  7211. };
  7212. /**
  7213. * Interpolates between min and max with smoothing at the limits.
  7214. *
  7215. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7216. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7217. */
  7218. Scalar.SmoothStep = function (from, to, tx) {
  7219. var t = Scalar.Clamp(tx);
  7220. t = -2.0 * t * t * t + 3.0 * t * t;
  7221. return to * t + from * (1.0 - t);
  7222. };
  7223. /**
  7224. * Moves a value current towards target.
  7225. *
  7226. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7227. * Negative values of maxDelta pushes the value away from target.
  7228. */
  7229. Scalar.MoveTowards = function (current, target, maxDelta) {
  7230. var result = 0;
  7231. if (Math.abs(target - current) <= maxDelta) {
  7232. result = target;
  7233. }
  7234. else {
  7235. result = current + Scalar.Sign(target - current) * maxDelta;
  7236. }
  7237. return result;
  7238. };
  7239. /**
  7240. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7241. *
  7242. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7243. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7244. */
  7245. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7246. var num = Scalar.DeltaAngle(current, target);
  7247. var result = 0;
  7248. if (-maxDelta < num && num < maxDelta) {
  7249. result = target;
  7250. }
  7251. else {
  7252. target = current + num;
  7253. result = Scalar.MoveTowards(current, target, maxDelta);
  7254. }
  7255. return result;
  7256. };
  7257. /**
  7258. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7259. */
  7260. Scalar.Lerp = function (start, end, amount) {
  7261. return start + ((end - start) * amount);
  7262. };
  7263. /**
  7264. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7265. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7266. */
  7267. Scalar.LerpAngle = function (start, end, amount) {
  7268. var num = Scalar.Repeat(end - start, 360.0);
  7269. if (num > 180.0) {
  7270. num -= 360.0;
  7271. }
  7272. return start + num * Scalar.Clamp(amount);
  7273. };
  7274. /**
  7275. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7276. */
  7277. Scalar.InverseLerp = function (a, b, value) {
  7278. var result = 0;
  7279. if (a != b) {
  7280. result = Scalar.Clamp((value - a) / (b - a));
  7281. }
  7282. else {
  7283. result = 0.0;
  7284. }
  7285. return result;
  7286. };
  7287. /**
  7288. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7289. */
  7290. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7291. var squared = amount * amount;
  7292. var cubed = amount * squared;
  7293. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7294. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7295. var part3 = (cubed - (2.0 * squared)) + amount;
  7296. var part4 = cubed - squared;
  7297. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7298. };
  7299. /**
  7300. * Returns a random float number between and min and max values
  7301. */
  7302. Scalar.RandomRange = function (min, max) {
  7303. if (min === max)
  7304. return min;
  7305. return ((Math.random() * (max - min)) + min);
  7306. };
  7307. /**
  7308. * This function returns percentage of a number in a given range.
  7309. *
  7310. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7311. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7312. */
  7313. Scalar.RangeToPercent = function (number, min, max) {
  7314. return ((number - min) / (max - min));
  7315. };
  7316. /**
  7317. * This function returns number that corresponds to the percentage in a given range.
  7318. *
  7319. * PercentToRange(0.34,0,100) will return 34.
  7320. */
  7321. Scalar.PercentToRange = function (percent, min, max) {
  7322. return ((max - min) * percent + min);
  7323. };
  7324. /**
  7325. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7326. * @param angle The angle to normalize in radian.
  7327. * @return The converted angle.
  7328. */
  7329. Scalar.NormalizeRadians = function (angle) {
  7330. // More precise but slower version kept for reference.
  7331. // angle = angle % Tools.TwoPi;
  7332. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7333. //if (angle > Math.PI) {
  7334. // angle -= Tools.TwoPi;
  7335. //}
  7336. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7337. return angle;
  7338. };
  7339. /**
  7340. * Two pi constants convenient for computation.
  7341. */
  7342. Scalar.TwoPi = Math.PI * 2;
  7343. return Scalar;
  7344. }());
  7345. BABYLON.Scalar = Scalar;
  7346. })(BABYLON || (BABYLON = {}));
  7347. //# sourceMappingURL=babylon.math.scalar.js.map
  7348. "use strict";
  7349. //# sourceMappingURL=babylon.mixins.js.map
  7350. "use strict";
  7351. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7352. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7353. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7354. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7355. //# sourceMappingURL=babylon.webgl2.js.map
  7356. "use strict";
  7357. var BABYLON;
  7358. (function (BABYLON) {
  7359. var __decoratorInitialStore = {};
  7360. var __mergedStore = {};
  7361. var _copySource = function (creationFunction, source, instanciate) {
  7362. var destination = creationFunction();
  7363. // Tags
  7364. if (BABYLON.Tags) {
  7365. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7366. }
  7367. var classStore = getMergedStore(destination);
  7368. // Properties
  7369. for (var property in classStore) {
  7370. var propertyDescriptor = classStore[property];
  7371. var sourceProperty = source[property];
  7372. var propertyType = propertyDescriptor.type;
  7373. if (sourceProperty !== undefined && sourceProperty !== null) {
  7374. switch (propertyType) {
  7375. case 0: // Value
  7376. case 6: // Mesh reference
  7377. case 11:// Camera reference
  7378. destination[property] = sourceProperty;
  7379. break;
  7380. case 1:// Texture
  7381. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7382. break;
  7383. case 2: // Color3
  7384. case 3: // FresnelParameters
  7385. case 4: // Vector2
  7386. case 5: // Vector3
  7387. case 7: // Color Curves
  7388. case 10:// Quaternion
  7389. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7390. break;
  7391. }
  7392. }
  7393. }
  7394. return destination;
  7395. };
  7396. function getDirectStore(target) {
  7397. var classKey = target.getClassName();
  7398. if (!__decoratorInitialStore[classKey]) {
  7399. __decoratorInitialStore[classKey] = {};
  7400. }
  7401. return __decoratorInitialStore[classKey];
  7402. }
  7403. /**
  7404. * Return the list of properties flagged as serializable
  7405. * @param target: host object
  7406. */
  7407. function getMergedStore(target) {
  7408. var classKey = target.getClassName();
  7409. if (__mergedStore[classKey]) {
  7410. return __mergedStore[classKey];
  7411. }
  7412. __mergedStore[classKey] = {};
  7413. var store = __mergedStore[classKey];
  7414. var currentTarget = target;
  7415. var currentKey = classKey;
  7416. while (currentKey) {
  7417. var initialStore = __decoratorInitialStore[currentKey];
  7418. for (var property in initialStore) {
  7419. store[property] = initialStore[property];
  7420. }
  7421. var parent_1 = void 0;
  7422. var done = false;
  7423. do {
  7424. parent_1 = Object.getPrototypeOf(currentTarget);
  7425. if (!parent_1.getClassName) {
  7426. done = true;
  7427. break;
  7428. }
  7429. if (parent_1.getClassName() !== currentKey) {
  7430. break;
  7431. }
  7432. currentTarget = parent_1;
  7433. } while (parent_1);
  7434. if (done) {
  7435. break;
  7436. }
  7437. currentKey = parent_1.getClassName();
  7438. currentTarget = parent_1;
  7439. }
  7440. return store;
  7441. }
  7442. function generateSerializableMember(type, sourceName) {
  7443. return function (target, propertyKey) {
  7444. var classStore = getDirectStore(target);
  7445. if (!classStore[propertyKey]) {
  7446. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7447. }
  7448. };
  7449. }
  7450. function generateExpandMember(setCallback, targetKey) {
  7451. if (targetKey === void 0) { targetKey = null; }
  7452. return function (target, propertyKey) {
  7453. var key = targetKey || ("_" + propertyKey);
  7454. Object.defineProperty(target, propertyKey, {
  7455. get: function () {
  7456. return this[key];
  7457. },
  7458. set: function (value) {
  7459. if (this[key] === value) {
  7460. return;
  7461. }
  7462. this[key] = value;
  7463. target[setCallback].apply(this);
  7464. },
  7465. enumerable: true,
  7466. configurable: true
  7467. });
  7468. };
  7469. }
  7470. function expandToProperty(callback, targetKey) {
  7471. if (targetKey === void 0) { targetKey = null; }
  7472. return generateExpandMember(callback, targetKey);
  7473. }
  7474. BABYLON.expandToProperty = expandToProperty;
  7475. function serialize(sourceName) {
  7476. return generateSerializableMember(0, sourceName); // value member
  7477. }
  7478. BABYLON.serialize = serialize;
  7479. function serializeAsTexture(sourceName) {
  7480. return generateSerializableMember(1, sourceName); // texture member
  7481. }
  7482. BABYLON.serializeAsTexture = serializeAsTexture;
  7483. function serializeAsColor3(sourceName) {
  7484. return generateSerializableMember(2, sourceName); // color3 member
  7485. }
  7486. BABYLON.serializeAsColor3 = serializeAsColor3;
  7487. function serializeAsFresnelParameters(sourceName) {
  7488. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7489. }
  7490. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7491. function serializeAsVector2(sourceName) {
  7492. return generateSerializableMember(4, sourceName); // vector2 member
  7493. }
  7494. BABYLON.serializeAsVector2 = serializeAsVector2;
  7495. function serializeAsVector3(sourceName) {
  7496. return generateSerializableMember(5, sourceName); // vector3 member
  7497. }
  7498. BABYLON.serializeAsVector3 = serializeAsVector3;
  7499. function serializeAsMeshReference(sourceName) {
  7500. return generateSerializableMember(6, sourceName); // mesh reference member
  7501. }
  7502. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7503. function serializeAsColorCurves(sourceName) {
  7504. return generateSerializableMember(7, sourceName); // color curves
  7505. }
  7506. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7507. function serializeAsColor4(sourceName) {
  7508. return generateSerializableMember(8, sourceName); // color 4
  7509. }
  7510. BABYLON.serializeAsColor4 = serializeAsColor4;
  7511. function serializeAsImageProcessingConfiguration(sourceName) {
  7512. return generateSerializableMember(9, sourceName); // image processing
  7513. }
  7514. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7515. function serializeAsQuaternion(sourceName) {
  7516. return generateSerializableMember(10, sourceName); // quaternion member
  7517. }
  7518. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7519. /**
  7520. * Decorator used to define property that can be serialized as reference to a camera
  7521. * @param sourceName defines the name of the property to decorate
  7522. */
  7523. function serializeAsCameraReference(sourceName) {
  7524. return generateSerializableMember(11, sourceName); // camera reference member
  7525. }
  7526. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7527. var SerializationHelper = /** @class */ (function () {
  7528. function SerializationHelper() {
  7529. }
  7530. SerializationHelper.Serialize = function (entity, serializationObject) {
  7531. if (!serializationObject) {
  7532. serializationObject = {};
  7533. }
  7534. // Tags
  7535. if (BABYLON.Tags) {
  7536. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7537. }
  7538. var serializedProperties = getMergedStore(entity);
  7539. // Properties
  7540. for (var property in serializedProperties) {
  7541. var propertyDescriptor = serializedProperties[property];
  7542. var targetPropertyName = propertyDescriptor.sourceName || property;
  7543. var propertyType = propertyDescriptor.type;
  7544. var sourceProperty = entity[property];
  7545. if (sourceProperty !== undefined && sourceProperty !== null) {
  7546. switch (propertyType) {
  7547. case 0:// Value
  7548. serializationObject[targetPropertyName] = sourceProperty;
  7549. break;
  7550. case 1:// Texture
  7551. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7552. break;
  7553. case 2:// Color3
  7554. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7555. break;
  7556. case 3:// FresnelParameters
  7557. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7558. break;
  7559. case 4:// Vector2
  7560. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7561. break;
  7562. case 5:// Vector3
  7563. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7564. break;
  7565. case 6:// Mesh reference
  7566. serializationObject[targetPropertyName] = sourceProperty.id;
  7567. break;
  7568. case 7:// Color Curves
  7569. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7570. break;
  7571. case 8:// Color 4
  7572. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7573. break;
  7574. case 9:// Image Processing
  7575. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7576. break;
  7577. case 10:// Quaternion
  7578. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7579. break;
  7580. case 11:// Camera reference
  7581. serializationObject[targetPropertyName] = sourceProperty.id;
  7582. break;
  7583. }
  7584. }
  7585. }
  7586. return serializationObject;
  7587. };
  7588. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7589. if (rootUrl === void 0) { rootUrl = null; }
  7590. var destination = creationFunction();
  7591. if (!rootUrl) {
  7592. rootUrl = "";
  7593. }
  7594. // Tags
  7595. if (BABYLON.Tags) {
  7596. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7597. }
  7598. var classStore = getMergedStore(destination);
  7599. // Properties
  7600. for (var property in classStore) {
  7601. var propertyDescriptor = classStore[property];
  7602. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7603. var propertyType = propertyDescriptor.type;
  7604. if (sourceProperty !== undefined && sourceProperty !== null) {
  7605. var dest = destination;
  7606. switch (propertyType) {
  7607. case 0:// Value
  7608. dest[property] = sourceProperty;
  7609. break;
  7610. case 1:// Texture
  7611. if (scene) {
  7612. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7613. }
  7614. break;
  7615. case 2:// Color3
  7616. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7617. break;
  7618. case 3:// FresnelParameters
  7619. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7620. break;
  7621. case 4:// Vector2
  7622. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7623. break;
  7624. case 5:// Vector3
  7625. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7626. break;
  7627. case 6:// Mesh reference
  7628. if (scene) {
  7629. dest[property] = scene.getLastMeshByID(sourceProperty);
  7630. }
  7631. break;
  7632. case 7:// Color Curves
  7633. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7634. break;
  7635. case 8:// Color 4
  7636. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7637. break;
  7638. case 9:// Image Processing
  7639. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7640. break;
  7641. case 10:// Quaternion
  7642. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7643. break;
  7644. case 11:// Camera reference
  7645. if (scene) {
  7646. dest[property] = scene.getCameraByID(sourceProperty);
  7647. }
  7648. break;
  7649. }
  7650. }
  7651. }
  7652. return destination;
  7653. };
  7654. SerializationHelper.Clone = function (creationFunction, source) {
  7655. return _copySource(creationFunction, source, false);
  7656. };
  7657. SerializationHelper.Instanciate = function (creationFunction, source) {
  7658. return _copySource(creationFunction, source, true);
  7659. };
  7660. return SerializationHelper;
  7661. }());
  7662. BABYLON.SerializationHelper = SerializationHelper;
  7663. })(BABYLON || (BABYLON = {}));
  7664. //# sourceMappingURL=babylon.decorators.js.map
  7665. "use strict";
  7666. var BABYLON;
  7667. (function (BABYLON) {
  7668. /**
  7669. * Wrapper class for promise with external resolve and reject.
  7670. */
  7671. var Deferred = /** @class */ (function () {
  7672. /**
  7673. * Constructor for this deferred object.
  7674. */
  7675. function Deferred() {
  7676. var _this = this;
  7677. this.promise = new Promise(function (resolve, reject) {
  7678. _this._resolve = resolve;
  7679. _this._reject = reject;
  7680. });
  7681. }
  7682. Object.defineProperty(Deferred.prototype, "resolve", {
  7683. /**
  7684. * The resolve method of the promise associated with this deferred object.
  7685. */
  7686. get: function () {
  7687. return this._resolve;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. Object.defineProperty(Deferred.prototype, "reject", {
  7693. /**
  7694. * The reject method of the promise associated with this deferred object.
  7695. */
  7696. get: function () {
  7697. return this._reject;
  7698. },
  7699. enumerable: true,
  7700. configurable: true
  7701. });
  7702. return Deferred;
  7703. }());
  7704. BABYLON.Deferred = Deferred;
  7705. })(BABYLON || (BABYLON = {}));
  7706. //# sourceMappingURL=babylon.deferred.js.map
  7707. "use strict";
  7708. var BABYLON;
  7709. (function (BABYLON) {
  7710. /**
  7711. * A class serves as a medium between the observable and its observers
  7712. */
  7713. var EventState = /** @class */ (function () {
  7714. /**
  7715. * Create a new EventState
  7716. * @param mask defines the mask associated with this state
  7717. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7718. * @param target defines the original target of the state
  7719. * @param currentTarget defines the current target of the state
  7720. */
  7721. function EventState(mask, skipNextObservers, target, currentTarget) {
  7722. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7723. this.initalize(mask, skipNextObservers, target, currentTarget);
  7724. }
  7725. /**
  7726. * Initialize the current event state
  7727. * @param mask defines the mask associated with this state
  7728. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7729. * @param target defines the original target of the state
  7730. * @param currentTarget defines the current target of the state
  7731. * @returns the current event state
  7732. */
  7733. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7734. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7735. this.mask = mask;
  7736. this.skipNextObservers = skipNextObservers;
  7737. this.target = target;
  7738. this.currentTarget = currentTarget;
  7739. return this;
  7740. };
  7741. return EventState;
  7742. }());
  7743. BABYLON.EventState = EventState;
  7744. /**
  7745. * Represent an Observer registered to a given Observable object.
  7746. */
  7747. var Observer = /** @class */ (function () {
  7748. /**
  7749. * Creates a new observer
  7750. * @param callback defines the callback to call when the observer is notified
  7751. * @param mask defines the mask of the observer (used to filter notifications)
  7752. * @param scope defines the current scope used to restore the JS context
  7753. */
  7754. function Observer(
  7755. /**
  7756. * Defines the callback to call when the observer is notified
  7757. */
  7758. callback,
  7759. /**
  7760. * Defines the mask of the observer (used to filter notifications)
  7761. */
  7762. mask,
  7763. /**
  7764. * Defines the current scope used to restore the JS context
  7765. */
  7766. scope) {
  7767. if (scope === void 0) { scope = null; }
  7768. this.callback = callback;
  7769. this.mask = mask;
  7770. this.scope = scope;
  7771. /** @ignore */
  7772. this._willBeUnregistered = false;
  7773. /**
  7774. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7775. */
  7776. this.unregisterOnNextCall = false;
  7777. }
  7778. return Observer;
  7779. }());
  7780. BABYLON.Observer = Observer;
  7781. /**
  7782. * Represent a list of observers registered to multiple Observables object.
  7783. */
  7784. var MultiObserver = /** @class */ (function () {
  7785. function MultiObserver() {
  7786. }
  7787. /**
  7788. * Release associated resources
  7789. */
  7790. MultiObserver.prototype.dispose = function () {
  7791. if (this._observers && this._observables) {
  7792. for (var index = 0; index < this._observers.length; index++) {
  7793. this._observables[index].remove(this._observers[index]);
  7794. }
  7795. }
  7796. this._observers = null;
  7797. this._observables = null;
  7798. };
  7799. /**
  7800. * Raise a callback when one of the observable will notify
  7801. * @param observables defines a list of observables to watch
  7802. * @param callback defines the callback to call on notification
  7803. * @param mask defines the mask used to filter notifications
  7804. * @param scope defines the current scope used to restore the JS context
  7805. * @returns the new MultiObserver
  7806. */
  7807. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7808. if (mask === void 0) { mask = -1; }
  7809. if (scope === void 0) { scope = null; }
  7810. var result = new MultiObserver();
  7811. result._observers = new Array();
  7812. result._observables = observables;
  7813. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7814. var observable = observables_1[_i];
  7815. var observer = observable.add(callback, mask, false, scope);
  7816. if (observer) {
  7817. result._observers.push(observer);
  7818. }
  7819. }
  7820. return result;
  7821. };
  7822. return MultiObserver;
  7823. }());
  7824. BABYLON.MultiObserver = MultiObserver;
  7825. /**
  7826. * The Observable class is a simple implementation of the Observable pattern.
  7827. *
  7828. * 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.
  7829. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7830. * 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).
  7831. * 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.
  7832. */
  7833. var Observable = /** @class */ (function () {
  7834. /**
  7835. * Creates a new observable
  7836. * @param onObserverAdded defines a callback to call when a new observer is added
  7837. */
  7838. function Observable(onObserverAdded) {
  7839. this._observers = new Array();
  7840. this._eventState = new EventState(0);
  7841. if (onObserverAdded) {
  7842. this._onObserverAdded = onObserverAdded;
  7843. }
  7844. }
  7845. /**
  7846. * Create a new Observer with the specified callback
  7847. * @param callback the callback that will be executed for that Observer
  7848. * @param mask the mask used to filter observers
  7849. * @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.
  7850. * @param scope optional scope for the callback to be called from
  7851. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7852. * @returns the new observer created for the callback
  7853. */
  7854. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7855. if (mask === void 0) { mask = -1; }
  7856. if (insertFirst === void 0) { insertFirst = false; }
  7857. if (scope === void 0) { scope = null; }
  7858. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7859. if (!callback) {
  7860. return null;
  7861. }
  7862. var observer = new Observer(callback, mask, scope);
  7863. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7864. if (insertFirst) {
  7865. this._observers.unshift(observer);
  7866. }
  7867. else {
  7868. this._observers.push(observer);
  7869. }
  7870. if (this._onObserverAdded) {
  7871. this._onObserverAdded(observer);
  7872. }
  7873. return observer;
  7874. };
  7875. /**
  7876. * Remove an Observer from the Observable object
  7877. * @param observer the instance of the Observer to remove
  7878. * @returns false if it doesn't belong to this Observable
  7879. */
  7880. Observable.prototype.remove = function (observer) {
  7881. if (!observer) {
  7882. return false;
  7883. }
  7884. var index = this._observers.indexOf(observer);
  7885. if (index !== -1) {
  7886. this._observers.splice(index, 1);
  7887. return true;
  7888. }
  7889. return false;
  7890. };
  7891. /**
  7892. * Remove a callback from the Observable object
  7893. * @param callback the callback to remove
  7894. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7895. * @returns false if it doesn't belong to this Observable
  7896. */
  7897. Observable.prototype.removeCallback = function (callback, scope) {
  7898. for (var index = 0; index < this._observers.length; index++) {
  7899. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7900. this._observers.splice(index, 1);
  7901. return true;
  7902. }
  7903. }
  7904. return false;
  7905. };
  7906. Observable.prototype._deferUnregister = function (observer) {
  7907. var _this = this;
  7908. observer.unregisterOnNextCall = false;
  7909. observer._willBeUnregistered = true;
  7910. BABYLON.Tools.SetImmediate(function () {
  7911. _this.remove(observer);
  7912. });
  7913. };
  7914. /**
  7915. * Notify all Observers by calling their respective callback with the given data
  7916. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7917. * @param eventData defines the data to send to all observers
  7918. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7919. * @param target defines the original target of the state
  7920. * @param currentTarget defines the current target of the state
  7921. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7922. */
  7923. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7924. if (mask === void 0) { mask = -1; }
  7925. if (!this._observers.length) {
  7926. return true;
  7927. }
  7928. var state = this._eventState;
  7929. state.mask = mask;
  7930. state.target = target;
  7931. state.currentTarget = currentTarget;
  7932. state.skipNextObservers = false;
  7933. state.lastReturnValue = eventData;
  7934. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7935. var obs = _a[_i];
  7936. if (obs._willBeUnregistered) {
  7937. continue;
  7938. }
  7939. if (obs.mask & mask) {
  7940. if (obs.scope) {
  7941. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7942. }
  7943. else {
  7944. state.lastReturnValue = obs.callback(eventData, state);
  7945. }
  7946. if (obs.unregisterOnNextCall) {
  7947. this._deferUnregister(obs);
  7948. }
  7949. }
  7950. if (state.skipNextObservers) {
  7951. return false;
  7952. }
  7953. }
  7954. return true;
  7955. };
  7956. /**
  7957. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7958. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7959. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7960. * and it is crucial that all callbacks will be executed.
  7961. * The order of the callbacks is kept, callbacks are not executed parallel.
  7962. *
  7963. * @param eventData The data to be sent to each callback
  7964. * @param mask is used to filter observers defaults to -1
  7965. * @param target defines the callback target (see EventState)
  7966. * @param currentTarget defines he current object in the bubbling phase
  7967. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7968. */
  7969. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7970. var _this = this;
  7971. if (mask === void 0) { mask = -1; }
  7972. // create an empty promise
  7973. var p = Promise.resolve(eventData);
  7974. // no observers? return this promise.
  7975. if (!this._observers.length) {
  7976. return p;
  7977. }
  7978. var state = this._eventState;
  7979. state.mask = mask;
  7980. state.target = target;
  7981. state.currentTarget = currentTarget;
  7982. state.skipNextObservers = false;
  7983. // execute one callback after another (not using Promise.all, the order is important)
  7984. this._observers.forEach(function (obs) {
  7985. if (state.skipNextObservers) {
  7986. return;
  7987. }
  7988. if (obs._willBeUnregistered) {
  7989. return;
  7990. }
  7991. if (obs.mask & mask) {
  7992. if (obs.scope) {
  7993. p = p.then(function (lastReturnedValue) {
  7994. state.lastReturnValue = lastReturnedValue;
  7995. return obs.callback.apply(obs.scope, [eventData, state]);
  7996. });
  7997. }
  7998. else {
  7999. p = p.then(function (lastReturnedValue) {
  8000. state.lastReturnValue = lastReturnedValue;
  8001. return obs.callback(eventData, state);
  8002. });
  8003. }
  8004. if (obs.unregisterOnNextCall) {
  8005. _this._deferUnregister(obs);
  8006. }
  8007. }
  8008. });
  8009. // return the eventData
  8010. return p.then(function () { return eventData; });
  8011. };
  8012. /**
  8013. * Notify a specific observer
  8014. * @param observer defines the observer to notify
  8015. * @param eventData defines the data to be sent to each callback
  8016. * @param mask is used to filter observers defaults to -1
  8017. */
  8018. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8019. if (mask === void 0) { mask = -1; }
  8020. var state = this._eventState;
  8021. state.mask = mask;
  8022. state.skipNextObservers = false;
  8023. observer.callback(eventData, state);
  8024. };
  8025. /**
  8026. * Gets a boolean indicating if the observable has at least one observer
  8027. * @returns true is the Observable has at least one Observer registered
  8028. */
  8029. Observable.prototype.hasObservers = function () {
  8030. return this._observers.length > 0;
  8031. };
  8032. /**
  8033. * Clear the list of observers
  8034. */
  8035. Observable.prototype.clear = function () {
  8036. this._observers = new Array();
  8037. this._onObserverAdded = null;
  8038. };
  8039. /**
  8040. * Clone the current observable
  8041. * @returns a new observable
  8042. */
  8043. Observable.prototype.clone = function () {
  8044. var result = new Observable();
  8045. result._observers = this._observers.slice(0);
  8046. return result;
  8047. };
  8048. /**
  8049. * Does this observable handles observer registered with a given mask
  8050. * @param mask defines the mask to be tested
  8051. * @return whether or not one observer registered with the given mask is handeled
  8052. **/
  8053. Observable.prototype.hasSpecificMask = function (mask) {
  8054. if (mask === void 0) { mask = -1; }
  8055. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8056. var obs = _a[_i];
  8057. if (obs.mask & mask || obs.mask === mask) {
  8058. return true;
  8059. }
  8060. }
  8061. return false;
  8062. };
  8063. return Observable;
  8064. }());
  8065. BABYLON.Observable = Observable;
  8066. })(BABYLON || (BABYLON = {}));
  8067. //# sourceMappingURL=babylon.observable.js.map
  8068. "use strict";
  8069. var BABYLON;
  8070. (function (BABYLON) {
  8071. var SmartArray = /** @class */ (function () {
  8072. function SmartArray(capacity) {
  8073. this.length = 0;
  8074. this.data = new Array(capacity);
  8075. this._id = SmartArray._GlobalId++;
  8076. }
  8077. SmartArray.prototype.push = function (value) {
  8078. this.data[this.length++] = value;
  8079. if (this.length > this.data.length) {
  8080. this.data.length *= 2;
  8081. }
  8082. };
  8083. SmartArray.prototype.forEach = function (func) {
  8084. for (var index = 0; index < this.length; index++) {
  8085. func(this.data[index]);
  8086. }
  8087. };
  8088. SmartArray.prototype.sort = function (compareFn) {
  8089. this.data.sort(compareFn);
  8090. };
  8091. SmartArray.prototype.reset = function () {
  8092. this.length = 0;
  8093. };
  8094. SmartArray.prototype.dispose = function () {
  8095. this.reset();
  8096. if (this.data) {
  8097. this.data.length = 0;
  8098. this.data = [];
  8099. }
  8100. };
  8101. SmartArray.prototype.concat = function (array) {
  8102. if (array.length === 0) {
  8103. return;
  8104. }
  8105. if (this.length + array.length > this.data.length) {
  8106. this.data.length = (this.length + array.length) * 2;
  8107. }
  8108. for (var index = 0; index < array.length; index++) {
  8109. this.data[this.length++] = (array.data || array)[index];
  8110. }
  8111. };
  8112. SmartArray.prototype.indexOf = function (value) {
  8113. var position = this.data.indexOf(value);
  8114. if (position >= this.length) {
  8115. return -1;
  8116. }
  8117. return position;
  8118. };
  8119. SmartArray.prototype.contains = function (value) {
  8120. return this.data.indexOf(value) !== -1;
  8121. };
  8122. // Statics
  8123. SmartArray._GlobalId = 0;
  8124. return SmartArray;
  8125. }());
  8126. BABYLON.SmartArray = SmartArray;
  8127. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8128. __extends(SmartArrayNoDuplicate, _super);
  8129. function SmartArrayNoDuplicate() {
  8130. var _this = _super !== null && _super.apply(this, arguments) || this;
  8131. _this._duplicateId = 0;
  8132. return _this;
  8133. }
  8134. SmartArrayNoDuplicate.prototype.push = function (value) {
  8135. _super.prototype.push.call(this, value);
  8136. if (!value.__smartArrayFlags) {
  8137. value.__smartArrayFlags = {};
  8138. }
  8139. value.__smartArrayFlags[this._id] = this._duplicateId;
  8140. };
  8141. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8142. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8143. return false;
  8144. }
  8145. this.push(value);
  8146. return true;
  8147. };
  8148. SmartArrayNoDuplicate.prototype.reset = function () {
  8149. _super.prototype.reset.call(this);
  8150. this._duplicateId++;
  8151. };
  8152. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8153. if (array.length === 0) {
  8154. return;
  8155. }
  8156. if (this.length + array.length > this.data.length) {
  8157. this.data.length = (this.length + array.length) * 2;
  8158. }
  8159. for (var index = 0; index < array.length; index++) {
  8160. var item = (array.data || array)[index];
  8161. this.pushNoDuplicate(item);
  8162. }
  8163. };
  8164. return SmartArrayNoDuplicate;
  8165. }(SmartArray));
  8166. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8167. })(BABYLON || (BABYLON = {}));
  8168. //# sourceMappingURL=babylon.smartArray.js.map
  8169. "use strict";
  8170. var BABYLON;
  8171. (function (BABYLON) {
  8172. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8173. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8174. var LoadFileError = /** @class */ (function (_super) {
  8175. __extends(LoadFileError, _super);
  8176. function LoadFileError(message, request) {
  8177. var _this = _super.call(this, message) || this;
  8178. _this.request = request;
  8179. _this.name = "LoadFileError";
  8180. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8181. return _this;
  8182. }
  8183. // Polyfill for Object.setPrototypeOf if necessary.
  8184. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8185. return LoadFileError;
  8186. }(Error));
  8187. BABYLON.LoadFileError = LoadFileError;
  8188. var RetryStrategy = /** @class */ (function () {
  8189. function RetryStrategy() {
  8190. }
  8191. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8192. if (maxRetries === void 0) { maxRetries = 3; }
  8193. if (baseInterval === void 0) { baseInterval = 500; }
  8194. return function (url, request, retryIndex) {
  8195. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8196. return -1;
  8197. }
  8198. return Math.pow(2, retryIndex) * baseInterval;
  8199. };
  8200. };
  8201. return RetryStrategy;
  8202. }());
  8203. BABYLON.RetryStrategy = RetryStrategy;
  8204. // Screenshots
  8205. var screenshotCanvas;
  8206. var cloneValue = function (source, destinationObject) {
  8207. if (!source)
  8208. return null;
  8209. if (source instanceof BABYLON.Mesh) {
  8210. return null;
  8211. }
  8212. if (source instanceof BABYLON.SubMesh) {
  8213. return source.clone(destinationObject);
  8214. }
  8215. else if (source.clone) {
  8216. return source.clone();
  8217. }
  8218. return null;
  8219. };
  8220. var Tools = /** @class */ (function () {
  8221. function Tools() {
  8222. }
  8223. /**
  8224. * Interpolates between a and b via alpha
  8225. * @param a The lower value (returned when alpha = 0)
  8226. * @param b The upper value (returned when alpha = 1)
  8227. * @param alpha The interpolation-factor
  8228. * @return The mixed value
  8229. */
  8230. Tools.Mix = function (a, b, alpha) {
  8231. return a * (1 - alpha) + b * alpha;
  8232. };
  8233. Tools.Instantiate = function (className) {
  8234. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8235. return Tools.RegisteredExternalClasses[className];
  8236. }
  8237. var arr = className.split(".");
  8238. var fn = (window || this);
  8239. for (var i = 0, len = arr.length; i < len; i++) {
  8240. fn = fn[arr[i]];
  8241. }
  8242. if (typeof fn !== "function") {
  8243. return null;
  8244. }
  8245. return fn;
  8246. };
  8247. /**
  8248. * Provides a slice function that will work even on IE
  8249. * @param data defines the array to slice
  8250. * @param start defines the start of the data (optional)
  8251. * @param end defines the end of the data (optional)
  8252. * @returns the new sliced array
  8253. */
  8254. Tools.Slice = function (data, start, end) {
  8255. if (data.slice) {
  8256. return data.slice(start, end);
  8257. }
  8258. return Array.prototype.slice.call(data, start, end);
  8259. };
  8260. Tools.SetImmediate = function (action) {
  8261. if (window.setImmediate) {
  8262. window.setImmediate(action);
  8263. }
  8264. else {
  8265. setTimeout(action, 1);
  8266. }
  8267. };
  8268. Tools.IsExponentOfTwo = function (value) {
  8269. var count = 1;
  8270. do {
  8271. count *= 2;
  8272. } while (count < value);
  8273. return count === value;
  8274. };
  8275. /**
  8276. * Find the next highest power of two.
  8277. * @param x Number to start search from.
  8278. * @return Next highest power of two.
  8279. */
  8280. Tools.CeilingPOT = function (x) {
  8281. x--;
  8282. x |= x >> 1;
  8283. x |= x >> 2;
  8284. x |= x >> 4;
  8285. x |= x >> 8;
  8286. x |= x >> 16;
  8287. x++;
  8288. return x;
  8289. };
  8290. /**
  8291. * Find the next lowest power of two.
  8292. * @param x Number to start search from.
  8293. * @return Next lowest power of two.
  8294. */
  8295. Tools.FloorPOT = function (x) {
  8296. x = x | (x >> 1);
  8297. x = x | (x >> 2);
  8298. x = x | (x >> 4);
  8299. x = x | (x >> 8);
  8300. x = x | (x >> 16);
  8301. return x - (x >> 1);
  8302. };
  8303. /**
  8304. * Find the nearest power of two.
  8305. * @param x Number to start search from.
  8306. * @return Next nearest power of two.
  8307. */
  8308. Tools.NearestPOT = function (x) {
  8309. var c = Tools.CeilingPOT(x);
  8310. var f = Tools.FloorPOT(x);
  8311. return (c - x) > (x - f) ? f : c;
  8312. };
  8313. Tools.GetExponentOfTwo = function (value, max, mode) {
  8314. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8315. var pot;
  8316. switch (mode) {
  8317. case BABYLON.Engine.SCALEMODE_FLOOR:
  8318. pot = Tools.FloorPOT(value);
  8319. break;
  8320. case BABYLON.Engine.SCALEMODE_NEAREST:
  8321. pot = Tools.NearestPOT(value);
  8322. break;
  8323. case BABYLON.Engine.SCALEMODE_CEILING:
  8324. default:
  8325. pot = Tools.CeilingPOT(value);
  8326. break;
  8327. }
  8328. return Math.min(pot, max);
  8329. };
  8330. Tools.GetFilename = function (path) {
  8331. var index = path.lastIndexOf("/");
  8332. if (index < 0)
  8333. return path;
  8334. return path.substring(index + 1);
  8335. };
  8336. /**
  8337. * Extracts the "folder" part of a path (everything before the filename).
  8338. * @param uri The URI to extract the info from
  8339. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8340. * @returns The "folder" part of the path
  8341. */
  8342. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8343. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8344. var index = uri.lastIndexOf("/");
  8345. if (index < 0) {
  8346. if (returnUnchangedIfNoSlash) {
  8347. return uri;
  8348. }
  8349. return "";
  8350. }
  8351. return uri.substring(0, index + 1);
  8352. };
  8353. Tools.GetDOMTextContent = function (element) {
  8354. var result = "";
  8355. var child = element.firstChild;
  8356. while (child) {
  8357. if (child.nodeType === 3) {
  8358. result += child.textContent;
  8359. }
  8360. child = child.nextSibling;
  8361. }
  8362. return result;
  8363. };
  8364. Tools.ToDegrees = function (angle) {
  8365. return angle * 180 / Math.PI;
  8366. };
  8367. Tools.ToRadians = function (angle) {
  8368. return angle * Math.PI / 180;
  8369. };
  8370. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8371. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8372. var output = "";
  8373. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8374. var i = 0;
  8375. var bytes = new Uint8Array(buffer);
  8376. while (i < bytes.length) {
  8377. chr1 = bytes[i++];
  8378. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8379. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8380. enc1 = chr1 >> 2;
  8381. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8382. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8383. enc4 = chr3 & 63;
  8384. if (isNaN(chr2)) {
  8385. enc3 = enc4 = 64;
  8386. }
  8387. else if (isNaN(chr3)) {
  8388. enc4 = 64;
  8389. }
  8390. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8391. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8392. }
  8393. return "data:image/png;base64," + output;
  8394. };
  8395. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8396. if (bias === void 0) { bias = null; }
  8397. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8398. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8399. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8400. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8401. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8402. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8403. }
  8404. if (bias) {
  8405. minimum.x -= minimum.x * bias.x + bias.y;
  8406. minimum.y -= minimum.y * bias.x + bias.y;
  8407. minimum.z -= minimum.z * bias.x + bias.y;
  8408. maximum.x += maximum.x * bias.x + bias.y;
  8409. maximum.y += maximum.y * bias.x + bias.y;
  8410. maximum.z += maximum.z * bias.x + bias.y;
  8411. }
  8412. return {
  8413. minimum: minimum,
  8414. maximum: maximum
  8415. };
  8416. };
  8417. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8418. if (bias === void 0) { bias = null; }
  8419. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8420. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8421. if (!stride) {
  8422. stride = 3;
  8423. }
  8424. for (var index = start; index < start + count; index++) {
  8425. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8426. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8427. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8428. }
  8429. if (bias) {
  8430. minimum.x -= minimum.x * bias.x + bias.y;
  8431. minimum.y -= minimum.y * bias.x + bias.y;
  8432. minimum.z -= minimum.z * bias.x + bias.y;
  8433. maximum.x += maximum.x * bias.x + bias.y;
  8434. maximum.y += maximum.y * bias.x + bias.y;
  8435. maximum.z += maximum.z * bias.x + bias.y;
  8436. }
  8437. return {
  8438. minimum: minimum,
  8439. maximum: maximum
  8440. };
  8441. };
  8442. Tools.Vector2ArrayFeeder = function (array) {
  8443. return function (index) {
  8444. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8445. var length = isFloatArray ? array.length / 2 : array.length;
  8446. if (index >= length) {
  8447. return null;
  8448. }
  8449. if (isFloatArray) {
  8450. var fa = array;
  8451. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8452. }
  8453. var a = array;
  8454. return a[index];
  8455. };
  8456. };
  8457. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8458. if (bias === void 0) { bias = null; }
  8459. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8460. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8461. var i = 0;
  8462. var cur = feeder(i++);
  8463. while (cur) {
  8464. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8465. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8466. cur = feeder(i++);
  8467. }
  8468. if (bias) {
  8469. minimum.x -= minimum.x * bias.x + bias.y;
  8470. minimum.y -= minimum.y * bias.x + bias.y;
  8471. maximum.x += maximum.x * bias.x + bias.y;
  8472. maximum.y += maximum.y * bias.x + bias.y;
  8473. }
  8474. return {
  8475. minimum: minimum,
  8476. maximum: maximum
  8477. };
  8478. };
  8479. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8480. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8481. return null;
  8482. return Array.isArray(obj) ? obj : [obj];
  8483. };
  8484. // Misc.
  8485. Tools.GetPointerPrefix = function () {
  8486. var eventPrefix = "pointer";
  8487. // Check if pointer events are supported
  8488. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8489. eventPrefix = "mouse";
  8490. }
  8491. return eventPrefix;
  8492. };
  8493. /**
  8494. * @param func - the function to be called
  8495. * @param requester - the object that will request the next frame. Falls back to window.
  8496. */
  8497. Tools.QueueNewFrame = function (func, requester) {
  8498. if (!Tools.IsWindowObjectExist()) {
  8499. return setTimeout(func, 16);
  8500. }
  8501. if (!requester) {
  8502. requester = window;
  8503. }
  8504. if (requester.requestAnimationFrame) {
  8505. return requester.requestAnimationFrame(func);
  8506. }
  8507. else if (requester.msRequestAnimationFrame) {
  8508. return requester.msRequestAnimationFrame(func);
  8509. }
  8510. else if (requester.webkitRequestAnimationFrame) {
  8511. return requester.webkitRequestAnimationFrame(func);
  8512. }
  8513. else if (requester.mozRequestAnimationFrame) {
  8514. return requester.mozRequestAnimationFrame(func);
  8515. }
  8516. else if (requester.oRequestAnimationFrame) {
  8517. return requester.oRequestAnimationFrame(func);
  8518. }
  8519. else {
  8520. return window.setTimeout(func, 16);
  8521. }
  8522. };
  8523. Tools.RequestFullscreen = function (element) {
  8524. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8525. if (!requestFunction)
  8526. return;
  8527. requestFunction.call(element);
  8528. };
  8529. Tools.ExitFullscreen = function () {
  8530. if (document.exitFullscreen) {
  8531. document.exitFullscreen();
  8532. }
  8533. else if (document.mozCancelFullScreen) {
  8534. document.mozCancelFullScreen();
  8535. }
  8536. else if (document.webkitCancelFullScreen) {
  8537. document.webkitCancelFullScreen();
  8538. }
  8539. else if (document.msCancelFullScreen) {
  8540. document.msCancelFullScreen();
  8541. }
  8542. };
  8543. Tools.SetCorsBehavior = function (url, element) {
  8544. if (url && url.indexOf("data:") === 0) {
  8545. return;
  8546. }
  8547. if (Tools.CorsBehavior) {
  8548. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8549. element.crossOrigin = Tools.CorsBehavior;
  8550. }
  8551. else {
  8552. var result = Tools.CorsBehavior(url);
  8553. if (result) {
  8554. element.crossOrigin = result;
  8555. }
  8556. }
  8557. }
  8558. };
  8559. // External files
  8560. Tools.CleanUrl = function (url) {
  8561. url = url.replace(/#/mg, "%23");
  8562. return url;
  8563. };
  8564. Tools.LoadImage = function (url, onLoad, onError, database) {
  8565. if (url instanceof ArrayBuffer) {
  8566. url = Tools.EncodeArrayBufferTobase64(url);
  8567. }
  8568. url = Tools.CleanUrl(url);
  8569. url = Tools.PreprocessUrl(url);
  8570. var img = new Image();
  8571. Tools.SetCorsBehavior(url, img);
  8572. var loadHandler = function () {
  8573. img.removeEventListener("load", loadHandler);
  8574. img.removeEventListener("error", errorHandler);
  8575. onLoad(img);
  8576. };
  8577. var errorHandler = function (err) {
  8578. img.removeEventListener("load", loadHandler);
  8579. img.removeEventListener("error", errorHandler);
  8580. Tools.Error("Error while trying to load image: " + url);
  8581. if (onError) {
  8582. onError("Error while trying to load image: " + url, err);
  8583. }
  8584. };
  8585. img.addEventListener("load", loadHandler);
  8586. img.addEventListener("error", errorHandler);
  8587. var noIndexedDB = function () {
  8588. img.src = url;
  8589. };
  8590. var loadFromIndexedDB = function () {
  8591. if (database) {
  8592. database.loadImageFromDB(url, img);
  8593. }
  8594. };
  8595. //ANY database to do!
  8596. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8597. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8598. }
  8599. else {
  8600. if (url.indexOf("file:") !== -1) {
  8601. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8602. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8603. try {
  8604. var blobURL;
  8605. try {
  8606. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8607. }
  8608. catch (ex) {
  8609. // Chrome doesn't support oneTimeOnly parameter
  8610. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8611. }
  8612. img.src = blobURL;
  8613. }
  8614. catch (e) {
  8615. img.src = "";
  8616. }
  8617. return img;
  8618. }
  8619. }
  8620. noIndexedDB();
  8621. }
  8622. return img;
  8623. };
  8624. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8625. url = Tools.CleanUrl(url);
  8626. url = Tools.PreprocessUrl(url);
  8627. // If file and file input are set
  8628. if (url.indexOf("file:") !== -1) {
  8629. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8630. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8631. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8632. }
  8633. }
  8634. var loadUrl = Tools.BaseUrl + url;
  8635. var aborted = false;
  8636. var fileRequest = {
  8637. onCompleteObservable: new BABYLON.Observable(),
  8638. abort: function () { return aborted = true; },
  8639. };
  8640. var requestFile = function () {
  8641. var request = new XMLHttpRequest();
  8642. var retryHandle = null;
  8643. fileRequest.abort = function () {
  8644. aborted = true;
  8645. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8646. request.abort();
  8647. }
  8648. if (retryHandle !== null) {
  8649. clearTimeout(retryHandle);
  8650. retryHandle = null;
  8651. }
  8652. };
  8653. var retryLoop = function (retryIndex) {
  8654. request.open('GET', loadUrl, true);
  8655. if (useArrayBuffer) {
  8656. request.responseType = "arraybuffer";
  8657. }
  8658. if (onProgress) {
  8659. request.addEventListener("progress", onProgress);
  8660. }
  8661. var onLoadEnd = function () {
  8662. request.removeEventListener("loadend", onLoadEnd);
  8663. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8664. fileRequest.onCompleteObservable.clear();
  8665. };
  8666. request.addEventListener("loadend", onLoadEnd);
  8667. var onReadyStateChange = function () {
  8668. if (aborted) {
  8669. return;
  8670. }
  8671. // In case of undefined state in some browsers.
  8672. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8673. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8674. request.removeEventListener("readystatechange", onReadyStateChange);
  8675. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8676. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8677. return;
  8678. }
  8679. var retryStrategy = Tools.DefaultRetryStrategy;
  8680. if (retryStrategy) {
  8681. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8682. if (waitTime !== -1) {
  8683. // Prevent the request from completing for retry.
  8684. request.removeEventListener("loadend", onLoadEnd);
  8685. request = new XMLHttpRequest();
  8686. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8687. return;
  8688. }
  8689. }
  8690. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8691. if (onError) {
  8692. onError(request, e);
  8693. }
  8694. else {
  8695. throw e;
  8696. }
  8697. }
  8698. };
  8699. request.addEventListener("readystatechange", onReadyStateChange);
  8700. request.send();
  8701. };
  8702. retryLoop(0);
  8703. };
  8704. // Caching all files
  8705. if (database && database.enableSceneOffline) {
  8706. var noIndexedDB_1 = function () {
  8707. if (!aborted) {
  8708. requestFile();
  8709. }
  8710. };
  8711. var loadFromIndexedDB = function () {
  8712. // TODO: database needs to support aborting and should return a IFileRequest
  8713. if (aborted) {
  8714. return;
  8715. }
  8716. if (database) {
  8717. database.loadFileFromDB(url, function (data) {
  8718. if (!aborted) {
  8719. onSuccess(data);
  8720. }
  8721. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8722. }, onProgress ? function (event) {
  8723. if (!aborted) {
  8724. onProgress(event);
  8725. }
  8726. } : undefined, noIndexedDB_1, useArrayBuffer);
  8727. }
  8728. };
  8729. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8730. }
  8731. else {
  8732. requestFile();
  8733. }
  8734. return fileRequest;
  8735. };
  8736. /**
  8737. * Load a script (identified by an url). When the url returns, the
  8738. * content of this file is added into a new script element, attached to the DOM (body element)
  8739. */
  8740. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8741. var head = document.getElementsByTagName('head')[0];
  8742. var script = document.createElement('script');
  8743. script.type = 'text/javascript';
  8744. script.src = scriptUrl;
  8745. script.onload = function () {
  8746. if (onSuccess) {
  8747. onSuccess();
  8748. }
  8749. };
  8750. script.onerror = function (e) {
  8751. if (onError) {
  8752. onError("Unable to load script", e);
  8753. }
  8754. };
  8755. head.appendChild(script);
  8756. };
  8757. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8758. var reader = new FileReader();
  8759. var request = {
  8760. onCompleteObservable: new BABYLON.Observable(),
  8761. abort: function () { return reader.abort(); },
  8762. };
  8763. reader.onloadend = function (e) {
  8764. request.onCompleteObservable.notifyObservers(request);
  8765. };
  8766. reader.onload = function (e) {
  8767. //target doesn't have result from ts 1.3
  8768. callback(e.target['result']);
  8769. };
  8770. reader.onprogress = progressCallback;
  8771. reader.readAsDataURL(fileToLoad);
  8772. return request;
  8773. };
  8774. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8775. var reader = new FileReader();
  8776. var request = {
  8777. onCompleteObservable: new BABYLON.Observable(),
  8778. abort: function () { return reader.abort(); },
  8779. };
  8780. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8781. reader.onerror = function (e) {
  8782. Tools.Log("Error while reading file: " + fileToLoad.name);
  8783. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8784. };
  8785. reader.onload = function (e) {
  8786. //target doesn't have result from ts 1.3
  8787. callback(e.target['result']);
  8788. };
  8789. if (progressCallBack) {
  8790. reader.onprogress = progressCallBack;
  8791. }
  8792. if (!useArrayBuffer) {
  8793. // Asynchronous read
  8794. reader.readAsText(fileToLoad);
  8795. }
  8796. else {
  8797. reader.readAsArrayBuffer(fileToLoad);
  8798. }
  8799. return request;
  8800. };
  8801. //returns a downloadable url to a file content.
  8802. Tools.FileAsURL = function (content) {
  8803. var fileBlob = new Blob([content]);
  8804. var url = window.URL || window.webkitURL;
  8805. var link = url.createObjectURL(fileBlob);
  8806. return link;
  8807. };
  8808. // Misc.
  8809. Tools.Format = function (value, decimals) {
  8810. if (decimals === void 0) { decimals = 2; }
  8811. return value.toFixed(decimals);
  8812. };
  8813. Tools.CheckExtends = function (v, min, max) {
  8814. if (v.x < min.x)
  8815. min.x = v.x;
  8816. if (v.y < min.y)
  8817. min.y = v.y;
  8818. if (v.z < min.z)
  8819. min.z = v.z;
  8820. if (v.x > max.x)
  8821. max.x = v.x;
  8822. if (v.y > max.y)
  8823. max.y = v.y;
  8824. if (v.z > max.z)
  8825. max.z = v.z;
  8826. };
  8827. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8828. for (var prop in source) {
  8829. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8830. continue;
  8831. }
  8832. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8833. continue;
  8834. }
  8835. var sourceValue = source[prop];
  8836. var typeOfSourceValue = typeof sourceValue;
  8837. if (typeOfSourceValue === "function") {
  8838. continue;
  8839. }
  8840. try {
  8841. if (typeOfSourceValue === "object") {
  8842. if (sourceValue instanceof Array) {
  8843. destination[prop] = [];
  8844. if (sourceValue.length > 0) {
  8845. if (typeof sourceValue[0] == "object") {
  8846. for (var index = 0; index < sourceValue.length; index++) {
  8847. var clonedValue = cloneValue(sourceValue[index], destination);
  8848. if (destination[prop].indexOf(clonedValue) === -1) {
  8849. destination[prop].push(clonedValue);
  8850. }
  8851. }
  8852. }
  8853. else {
  8854. destination[prop] = sourceValue.slice(0);
  8855. }
  8856. }
  8857. }
  8858. else {
  8859. destination[prop] = cloneValue(sourceValue, destination);
  8860. }
  8861. }
  8862. else {
  8863. destination[prop] = sourceValue;
  8864. }
  8865. }
  8866. catch (e) {
  8867. // Just ignore error (it could be because of a read-only property)
  8868. }
  8869. }
  8870. };
  8871. Tools.IsEmpty = function (obj) {
  8872. for (var i in obj) {
  8873. if (obj.hasOwnProperty(i)) {
  8874. return false;
  8875. }
  8876. }
  8877. return true;
  8878. };
  8879. Tools.RegisterTopRootEvents = function (events) {
  8880. for (var index = 0; index < events.length; index++) {
  8881. var event = events[index];
  8882. window.addEventListener(event.name, event.handler, false);
  8883. try {
  8884. if (window.parent) {
  8885. window.parent.addEventListener(event.name, event.handler, false);
  8886. }
  8887. }
  8888. catch (e) {
  8889. // Silently fails...
  8890. }
  8891. }
  8892. };
  8893. Tools.UnregisterTopRootEvents = function (events) {
  8894. for (var index = 0; index < events.length; index++) {
  8895. var event = events[index];
  8896. window.removeEventListener(event.name, event.handler);
  8897. try {
  8898. if (window.parent) {
  8899. window.parent.removeEventListener(event.name, event.handler);
  8900. }
  8901. }
  8902. catch (e) {
  8903. // Silently fails...
  8904. }
  8905. }
  8906. };
  8907. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8908. if (mimeType === void 0) { mimeType = "image/png"; }
  8909. // Read the contents of the framebuffer
  8910. var numberOfChannelsByLine = width * 4;
  8911. var halfHeight = height / 2;
  8912. //Reading datas from WebGL
  8913. var data = engine.readPixels(0, 0, width, height);
  8914. //To flip image on Y axis.
  8915. for (var i = 0; i < halfHeight; i++) {
  8916. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8917. var currentCell = j + i * numberOfChannelsByLine;
  8918. var targetLine = height - i - 1;
  8919. var targetCell = j + targetLine * numberOfChannelsByLine;
  8920. var temp = data[currentCell];
  8921. data[currentCell] = data[targetCell];
  8922. data[targetCell] = temp;
  8923. }
  8924. }
  8925. // Create a 2D canvas to store the result
  8926. if (!screenshotCanvas) {
  8927. screenshotCanvas = document.createElement('canvas');
  8928. }
  8929. screenshotCanvas.width = width;
  8930. screenshotCanvas.height = height;
  8931. var context = screenshotCanvas.getContext('2d');
  8932. if (context) {
  8933. // Copy the pixels to a 2D canvas
  8934. var imageData = context.createImageData(width, height);
  8935. var castData = (imageData.data);
  8936. castData.set(data);
  8937. context.putImageData(imageData, 0, 0);
  8938. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8939. }
  8940. };
  8941. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8942. if (mimeType === void 0) { mimeType = "image/png"; }
  8943. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8944. if (successCallback) {
  8945. successCallback(base64Image);
  8946. }
  8947. else {
  8948. // We need HTMLCanvasElement.toBlob for HD screenshots
  8949. if (!screenshotCanvas.toBlob) {
  8950. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8951. screenshotCanvas.toBlob = function (callback, type, quality) {
  8952. var _this = this;
  8953. setTimeout(function () {
  8954. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8955. for (var i = 0; i < len; i++) {
  8956. arr[i] = binStr.charCodeAt(i);
  8957. }
  8958. callback(new Blob([arr], { type: type || 'image/png' }));
  8959. });
  8960. };
  8961. }
  8962. screenshotCanvas.toBlob(function (blob) {
  8963. var url = URL.createObjectURL(blob);
  8964. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8965. if (("download" in document.createElement("a"))) {
  8966. var a = window.document.createElement("a");
  8967. a.href = url;
  8968. if (fileName) {
  8969. a.setAttribute("download", fileName);
  8970. }
  8971. else {
  8972. var date = new Date();
  8973. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8974. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8975. }
  8976. window.document.body.appendChild(a);
  8977. a.addEventListener("click", function () {
  8978. if (a.parentElement) {
  8979. a.parentElement.removeChild(a);
  8980. }
  8981. });
  8982. a.click();
  8983. }
  8984. else {
  8985. var newWindow = window.open("");
  8986. if (!newWindow)
  8987. return;
  8988. var img = newWindow.document.createElement("img");
  8989. img.onload = function () {
  8990. // no longer need to read the blob so it's revoked
  8991. URL.revokeObjectURL(url);
  8992. };
  8993. img.src = url;
  8994. newWindow.document.body.appendChild(img);
  8995. }
  8996. });
  8997. }
  8998. };
  8999. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9000. if (mimeType === void 0) { mimeType = "image/png"; }
  9001. var width;
  9002. var height;
  9003. // If a precision value is specified
  9004. if (size.precision) {
  9005. width = Math.round(engine.getRenderWidth() * size.precision);
  9006. height = Math.round(width / engine.getAspectRatio(camera));
  9007. }
  9008. else if (size.width && size.height) {
  9009. width = size.width;
  9010. height = size.height;
  9011. }
  9012. else if (size.width && !size.height) {
  9013. width = size.width;
  9014. height = Math.round(width / engine.getAspectRatio(camera));
  9015. }
  9016. else if (size.height && !size.width) {
  9017. height = size.height;
  9018. width = Math.round(height * engine.getAspectRatio(camera));
  9019. }
  9020. else if (!isNaN(size)) {
  9021. height = size;
  9022. width = size;
  9023. }
  9024. else {
  9025. Tools.Error("Invalid 'size' parameter !");
  9026. return;
  9027. }
  9028. if (!screenshotCanvas) {
  9029. screenshotCanvas = document.createElement('canvas');
  9030. }
  9031. screenshotCanvas.width = width;
  9032. screenshotCanvas.height = height;
  9033. var renderContext = screenshotCanvas.getContext("2d");
  9034. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9035. var newWidth = width;
  9036. var newHeight = newWidth / ratio;
  9037. if (newHeight > height) {
  9038. newHeight = height;
  9039. newWidth = newHeight * ratio;
  9040. }
  9041. var offsetX = Math.max(0, width - newWidth) / 2;
  9042. var offsetY = Math.max(0, height - newHeight) / 2;
  9043. var renderingCanvas = engine.getRenderingCanvas();
  9044. if (renderContext && renderingCanvas) {
  9045. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9046. }
  9047. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9048. };
  9049. /**
  9050. * Generates an image screenshot from the specified camera.
  9051. *
  9052. * @param engine The engine to use for rendering
  9053. * @param camera The camera to use for rendering
  9054. * @param size This parameter can be set to a single number or to an object with the
  9055. * following (optional) properties: precision, width, height. If a single number is passed,
  9056. * it will be used for both width and height. If an object is passed, the screenshot size
  9057. * will be derived from the parameters. The precision property is a multiplier allowing
  9058. * rendering at a higher or lower resolution.
  9059. * @param successCallback The callback receives a single parameter which contains the
  9060. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9061. * src parameter of an <img> to display it.
  9062. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9063. * Check your browser for supported MIME types.
  9064. * @param samples Texture samples (default: 1)
  9065. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9066. * @param fileName A name for for the downloaded file.
  9067. * @constructor
  9068. */
  9069. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9070. if (mimeType === void 0) { mimeType = "image/png"; }
  9071. if (samples === void 0) { samples = 1; }
  9072. if (antialiasing === void 0) { antialiasing = false; }
  9073. var width;
  9074. var height;
  9075. //If a precision value is specified
  9076. if (size.precision) {
  9077. width = Math.round(engine.getRenderWidth() * size.precision);
  9078. height = Math.round(width / engine.getAspectRatio(camera));
  9079. size = { width: width, height: height };
  9080. }
  9081. else if (size.width && size.height) {
  9082. width = size.width;
  9083. height = size.height;
  9084. }
  9085. else if (size.width && !size.height) {
  9086. width = size.width;
  9087. height = Math.round(width / engine.getAspectRatio(camera));
  9088. size = { width: width, height: height };
  9089. }
  9090. else if (size.height && !size.width) {
  9091. height = size.height;
  9092. width = Math.round(height * engine.getAspectRatio(camera));
  9093. size = { width: width, height: height };
  9094. }
  9095. else if (!isNaN(size)) {
  9096. height = size;
  9097. width = size;
  9098. }
  9099. else {
  9100. Tools.Error("Invalid 'size' parameter !");
  9101. return;
  9102. }
  9103. var scene = camera.getScene();
  9104. var previousCamera = null;
  9105. if (scene.activeCamera !== camera) {
  9106. previousCamera = scene.activeCamera;
  9107. scene.activeCamera = camera;
  9108. }
  9109. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9110. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9111. texture.renderList = null;
  9112. texture.samples = samples;
  9113. if (antialiasing) {
  9114. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9115. }
  9116. texture.onAfterRenderObservable.add(function () {
  9117. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9118. });
  9119. scene.incrementRenderId();
  9120. scene.resetCachedMaterial();
  9121. texture.render(true);
  9122. texture.dispose();
  9123. if (previousCamera) {
  9124. scene.activeCamera = previousCamera;
  9125. }
  9126. camera.getProjectionMatrix(true); // Force cache refresh;
  9127. };
  9128. // XHR response validator for local file scenario
  9129. Tools.ValidateXHRData = function (xhr, dataType) {
  9130. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9131. if (dataType === void 0) { dataType = 7; }
  9132. try {
  9133. if (dataType & 1) {
  9134. if (xhr.responseText && xhr.responseText.length > 0) {
  9135. return true;
  9136. }
  9137. else if (dataType === 1) {
  9138. return false;
  9139. }
  9140. }
  9141. if (dataType & 2) {
  9142. // Check header width and height since there is no "TGA" magic number
  9143. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9144. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9145. return true;
  9146. }
  9147. else if (dataType === 2) {
  9148. return false;
  9149. }
  9150. }
  9151. if (dataType & 4) {
  9152. // Check for the "DDS" magic number
  9153. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9154. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9155. return true;
  9156. }
  9157. else {
  9158. return false;
  9159. }
  9160. }
  9161. }
  9162. catch (e) {
  9163. // Global protection
  9164. }
  9165. return false;
  9166. };
  9167. /**
  9168. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9169. * Be aware Math.random() could cause collisions, but:
  9170. * "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"
  9171. */
  9172. Tools.RandomId = function () {
  9173. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9174. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9175. return v.toString(16);
  9176. });
  9177. };
  9178. /**
  9179. * Test if the given uri is a base64 string.
  9180. * @param uri The uri to test
  9181. * @return True if the uri is a base64 string or false otherwise.
  9182. */
  9183. Tools.IsBase64 = function (uri) {
  9184. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9185. };
  9186. /**
  9187. * Decode the given base64 uri.
  9188. * @param uri The uri to decode
  9189. * @return The decoded base64 data.
  9190. */
  9191. Tools.DecodeBase64 = function (uri) {
  9192. var decodedString = atob(uri.split(",")[1]);
  9193. var bufferLength = decodedString.length;
  9194. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9195. for (var i = 0; i < bufferLength; i++) {
  9196. bufferView[i] = decodedString.charCodeAt(i);
  9197. }
  9198. return bufferView.buffer;
  9199. };
  9200. Object.defineProperty(Tools, "NoneLogLevel", {
  9201. get: function () {
  9202. return Tools._NoneLogLevel;
  9203. },
  9204. enumerable: true,
  9205. configurable: true
  9206. });
  9207. Object.defineProperty(Tools, "MessageLogLevel", {
  9208. get: function () {
  9209. return Tools._MessageLogLevel;
  9210. },
  9211. enumerable: true,
  9212. configurable: true
  9213. });
  9214. Object.defineProperty(Tools, "WarningLogLevel", {
  9215. get: function () {
  9216. return Tools._WarningLogLevel;
  9217. },
  9218. enumerable: true,
  9219. configurable: true
  9220. });
  9221. Object.defineProperty(Tools, "ErrorLogLevel", {
  9222. get: function () {
  9223. return Tools._ErrorLogLevel;
  9224. },
  9225. enumerable: true,
  9226. configurable: true
  9227. });
  9228. Object.defineProperty(Tools, "AllLogLevel", {
  9229. get: function () {
  9230. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9231. },
  9232. enumerable: true,
  9233. configurable: true
  9234. });
  9235. Tools._AddLogEntry = function (entry) {
  9236. Tools._LogCache = entry + Tools._LogCache;
  9237. if (Tools.OnNewCacheEntry) {
  9238. Tools.OnNewCacheEntry(entry);
  9239. }
  9240. };
  9241. Tools._FormatMessage = function (message) {
  9242. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9243. var date = new Date();
  9244. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9245. };
  9246. Tools._LogDisabled = function (message) {
  9247. // nothing to do
  9248. };
  9249. Tools._LogEnabled = function (message) {
  9250. var formattedMessage = Tools._FormatMessage(message);
  9251. console.log("BJS - " + formattedMessage);
  9252. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9253. Tools._AddLogEntry(entry);
  9254. };
  9255. Tools._WarnDisabled = function (message) {
  9256. // nothing to do
  9257. };
  9258. Tools._WarnEnabled = function (message) {
  9259. var formattedMessage = Tools._FormatMessage(message);
  9260. console.warn("BJS - " + formattedMessage);
  9261. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9262. Tools._AddLogEntry(entry);
  9263. };
  9264. Tools._ErrorDisabled = function (message) {
  9265. // nothing to do
  9266. };
  9267. Tools._ErrorEnabled = function (message) {
  9268. Tools.errorsCount++;
  9269. var formattedMessage = Tools._FormatMessage(message);
  9270. console.error("BJS - " + formattedMessage);
  9271. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9272. Tools._AddLogEntry(entry);
  9273. };
  9274. Object.defineProperty(Tools, "LogCache", {
  9275. get: function () {
  9276. return Tools._LogCache;
  9277. },
  9278. enumerable: true,
  9279. configurable: true
  9280. });
  9281. Tools.ClearLogCache = function () {
  9282. Tools._LogCache = "";
  9283. Tools.errorsCount = 0;
  9284. };
  9285. Object.defineProperty(Tools, "LogLevels", {
  9286. set: function (level) {
  9287. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9288. Tools.Log = Tools._LogEnabled;
  9289. }
  9290. else {
  9291. Tools.Log = Tools._LogDisabled;
  9292. }
  9293. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9294. Tools.Warn = Tools._WarnEnabled;
  9295. }
  9296. else {
  9297. Tools.Warn = Tools._WarnDisabled;
  9298. }
  9299. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9300. Tools.Error = Tools._ErrorEnabled;
  9301. }
  9302. else {
  9303. Tools.Error = Tools._ErrorDisabled;
  9304. }
  9305. },
  9306. enumerable: true,
  9307. configurable: true
  9308. });
  9309. Tools.IsWindowObjectExist = function () {
  9310. return (typeof window) !== "undefined";
  9311. };
  9312. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9313. get: function () {
  9314. return Tools._PerformanceNoneLogLevel;
  9315. },
  9316. enumerable: true,
  9317. configurable: true
  9318. });
  9319. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9320. get: function () {
  9321. return Tools._PerformanceUserMarkLogLevel;
  9322. },
  9323. enumerable: true,
  9324. configurable: true
  9325. });
  9326. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9327. get: function () {
  9328. return Tools._PerformanceConsoleLogLevel;
  9329. },
  9330. enumerable: true,
  9331. configurable: true
  9332. });
  9333. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9334. set: function (level) {
  9335. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9336. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9337. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9338. return;
  9339. }
  9340. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9341. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9342. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9343. return;
  9344. }
  9345. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9346. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9347. },
  9348. enumerable: true,
  9349. configurable: true
  9350. });
  9351. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9352. };
  9353. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9354. };
  9355. Tools._StartUserMark = function (counterName, condition) {
  9356. if (condition === void 0) { condition = true; }
  9357. if (!Tools._performance) {
  9358. if (!Tools.IsWindowObjectExist()) {
  9359. return;
  9360. }
  9361. Tools._performance = window.performance;
  9362. }
  9363. if (!condition || !Tools._performance.mark) {
  9364. return;
  9365. }
  9366. Tools._performance.mark(counterName + "-Begin");
  9367. };
  9368. Tools._EndUserMark = function (counterName, condition) {
  9369. if (condition === void 0) { condition = true; }
  9370. if (!condition || !Tools._performance.mark) {
  9371. return;
  9372. }
  9373. Tools._performance.mark(counterName + "-End");
  9374. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9375. };
  9376. Tools._StartPerformanceConsole = function (counterName, condition) {
  9377. if (condition === void 0) { condition = true; }
  9378. if (!condition) {
  9379. return;
  9380. }
  9381. Tools._StartUserMark(counterName, condition);
  9382. if (console.time) {
  9383. console.time(counterName);
  9384. }
  9385. };
  9386. Tools._EndPerformanceConsole = function (counterName, condition) {
  9387. if (condition === void 0) { condition = true; }
  9388. if (!condition) {
  9389. return;
  9390. }
  9391. Tools._EndUserMark(counterName, condition);
  9392. if (console.time) {
  9393. console.timeEnd(counterName);
  9394. }
  9395. };
  9396. Object.defineProperty(Tools, "Now", {
  9397. get: function () {
  9398. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9399. return window.performance.now();
  9400. }
  9401. return new Date().getTime();
  9402. },
  9403. enumerable: true,
  9404. configurable: true
  9405. });
  9406. /**
  9407. * This method will return the name of the class used to create the instance of the given object.
  9408. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9409. * @param object the object to get the class name from
  9410. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9411. */
  9412. Tools.GetClassName = function (object, isType) {
  9413. if (isType === void 0) { isType = false; }
  9414. var name = null;
  9415. if (!isType && object.getClassName) {
  9416. name = object.getClassName();
  9417. }
  9418. else {
  9419. if (object instanceof Object) {
  9420. var classObj = isType ? object : Object.getPrototypeOf(object);
  9421. name = classObj.constructor["__bjsclassName__"];
  9422. }
  9423. if (!name) {
  9424. name = typeof object;
  9425. }
  9426. }
  9427. return name;
  9428. };
  9429. Tools.First = function (array, predicate) {
  9430. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9431. var el = array_1[_i];
  9432. if (predicate(el)) {
  9433. return el;
  9434. }
  9435. }
  9436. return null;
  9437. };
  9438. /**
  9439. * This method will return the name of the full name of the class, including its owning module (if any).
  9440. * 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).
  9441. * @param object the object to get the class name from
  9442. * @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.
  9443. */
  9444. Tools.getFullClassName = function (object, isType) {
  9445. if (isType === void 0) { isType = false; }
  9446. var className = null;
  9447. var moduleName = null;
  9448. if (!isType && object.getClassName) {
  9449. className = object.getClassName();
  9450. }
  9451. else {
  9452. if (object instanceof Object) {
  9453. var classObj = isType ? object : Object.getPrototypeOf(object);
  9454. className = classObj.constructor["__bjsclassName__"];
  9455. moduleName = classObj.constructor["__bjsmoduleName__"];
  9456. }
  9457. if (!className) {
  9458. className = typeof object;
  9459. }
  9460. }
  9461. if (!className) {
  9462. return null;
  9463. }
  9464. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9465. };
  9466. /**
  9467. * 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.
  9468. * @param array
  9469. */
  9470. Tools.arrayOrStringFeeder = function (array) {
  9471. return function (index) {
  9472. if (index >= array.length) {
  9473. return null;
  9474. }
  9475. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9476. if (val && val.getHashCode) {
  9477. val = val.getHashCode();
  9478. }
  9479. if (typeof val === "string") {
  9480. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9481. }
  9482. return val;
  9483. };
  9484. };
  9485. /**
  9486. * Compute the hashCode of a stream of number
  9487. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9488. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9489. * @return the hash code computed
  9490. */
  9491. Tools.hashCodeFromStream = function (feeder) {
  9492. // Based from here: http://stackoverflow.com/a/7616484/802124
  9493. var hash = 0;
  9494. var index = 0;
  9495. var chr = feeder(index++);
  9496. while (chr != null) {
  9497. hash = ((hash << 5) - hash) + chr;
  9498. hash |= 0; // Convert to 32bit integer
  9499. chr = feeder(index++);
  9500. }
  9501. return hash;
  9502. };
  9503. /**
  9504. * Returns a promise that resolves after the given amount of time.
  9505. * @param delay Number of milliseconds to delay
  9506. * @returns Promise that resolves after the given amount of time
  9507. */
  9508. Tools.DelayAsync = function (delay) {
  9509. return new Promise(function (resolve) {
  9510. setTimeout(function () {
  9511. resolve();
  9512. }, delay);
  9513. });
  9514. };
  9515. Tools.BaseUrl = "";
  9516. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9517. /**
  9518. * Default behaviour for cors in the application.
  9519. * It can be a string if the expected behavior is identical in the entire app.
  9520. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9521. */
  9522. Tools.CorsBehavior = "anonymous";
  9523. Tools.UseFallbackTexture = true;
  9524. /**
  9525. * Use this object to register external classes like custom textures or material
  9526. * to allow the laoders to instantiate them
  9527. */
  9528. Tools.RegisteredExternalClasses = {};
  9529. // Used in case of a texture loading problem
  9530. 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";
  9531. Tools.PreprocessUrl = function (url) {
  9532. return url;
  9533. };
  9534. // Logs
  9535. Tools._NoneLogLevel = 0;
  9536. Tools._MessageLogLevel = 1;
  9537. Tools._WarningLogLevel = 2;
  9538. Tools._ErrorLogLevel = 4;
  9539. Tools._LogCache = "";
  9540. Tools.errorsCount = 0;
  9541. Tools.Log = Tools._LogEnabled;
  9542. Tools.Warn = Tools._WarnEnabled;
  9543. Tools.Error = Tools._ErrorEnabled;
  9544. // Performances
  9545. Tools._PerformanceNoneLogLevel = 0;
  9546. Tools._PerformanceUserMarkLogLevel = 1;
  9547. Tools._PerformanceConsoleLogLevel = 2;
  9548. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9549. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9550. return Tools;
  9551. }());
  9552. BABYLON.Tools = Tools;
  9553. /**
  9554. * This class is used to track a performance counter which is number based.
  9555. * The user has access to many properties which give statistics of different nature
  9556. *
  9557. * The implementer can track two kinds of Performance Counter: time and count
  9558. * 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.
  9559. * 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.
  9560. */
  9561. var PerfCounter = /** @class */ (function () {
  9562. function PerfCounter() {
  9563. this._startMonitoringTime = 0;
  9564. this._min = 0;
  9565. this._max = 0;
  9566. this._average = 0;
  9567. this._lastSecAverage = 0;
  9568. this._current = 0;
  9569. this._totalValueCount = 0;
  9570. this._totalAccumulated = 0;
  9571. this._lastSecAccumulated = 0;
  9572. this._lastSecTime = 0;
  9573. this._lastSecValueCount = 0;
  9574. }
  9575. Object.defineProperty(PerfCounter.prototype, "min", {
  9576. /**
  9577. * Returns the smallest value ever
  9578. */
  9579. get: function () {
  9580. return this._min;
  9581. },
  9582. enumerable: true,
  9583. configurable: true
  9584. });
  9585. Object.defineProperty(PerfCounter.prototype, "max", {
  9586. /**
  9587. * Returns the biggest value ever
  9588. */
  9589. get: function () {
  9590. return this._max;
  9591. },
  9592. enumerable: true,
  9593. configurable: true
  9594. });
  9595. Object.defineProperty(PerfCounter.prototype, "average", {
  9596. /**
  9597. * Returns the average value since the performance counter is running
  9598. */
  9599. get: function () {
  9600. return this._average;
  9601. },
  9602. enumerable: true,
  9603. configurable: true
  9604. });
  9605. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9606. /**
  9607. * Returns the average value of the last second the counter was monitored
  9608. */
  9609. get: function () {
  9610. return this._lastSecAverage;
  9611. },
  9612. enumerable: true,
  9613. configurable: true
  9614. });
  9615. Object.defineProperty(PerfCounter.prototype, "current", {
  9616. /**
  9617. * Returns the current value
  9618. */
  9619. get: function () {
  9620. return this._current;
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. Object.defineProperty(PerfCounter.prototype, "total", {
  9626. get: function () {
  9627. return this._totalAccumulated;
  9628. },
  9629. enumerable: true,
  9630. configurable: true
  9631. });
  9632. Object.defineProperty(PerfCounter.prototype, "count", {
  9633. get: function () {
  9634. return this._totalValueCount;
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. /**
  9640. * Call this method to start monitoring a new frame.
  9641. * 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.
  9642. */
  9643. PerfCounter.prototype.fetchNewFrame = function () {
  9644. this._totalValueCount++;
  9645. this._current = 0;
  9646. this._lastSecValueCount++;
  9647. };
  9648. /**
  9649. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9650. * @param newCount the count value to add to the monitored count
  9651. * @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.
  9652. */
  9653. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9654. if (!PerfCounter.Enabled) {
  9655. return;
  9656. }
  9657. this._current += newCount;
  9658. if (fetchResult) {
  9659. this._fetchResult();
  9660. }
  9661. };
  9662. /**
  9663. * Start monitoring this performance counter
  9664. */
  9665. PerfCounter.prototype.beginMonitoring = function () {
  9666. if (!PerfCounter.Enabled) {
  9667. return;
  9668. }
  9669. this._startMonitoringTime = Tools.Now;
  9670. };
  9671. /**
  9672. * Compute the time lapsed since the previous beginMonitoring() call.
  9673. * @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
  9674. */
  9675. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9676. if (newFrame === void 0) { newFrame = true; }
  9677. if (!PerfCounter.Enabled) {
  9678. return;
  9679. }
  9680. if (newFrame) {
  9681. this.fetchNewFrame();
  9682. }
  9683. var currentTime = Tools.Now;
  9684. this._current = currentTime - this._startMonitoringTime;
  9685. if (newFrame) {
  9686. this._fetchResult();
  9687. }
  9688. };
  9689. PerfCounter.prototype._fetchResult = function () {
  9690. this._totalAccumulated += this._current;
  9691. this._lastSecAccumulated += this._current;
  9692. // Min/Max update
  9693. this._min = Math.min(this._min, this._current);
  9694. this._max = Math.max(this._max, this._current);
  9695. this._average = this._totalAccumulated / this._totalValueCount;
  9696. // Reset last sec?
  9697. var now = Tools.Now;
  9698. if ((now - this._lastSecTime) > 1000) {
  9699. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9700. this._lastSecTime = now;
  9701. this._lastSecAccumulated = 0;
  9702. this._lastSecValueCount = 0;
  9703. }
  9704. };
  9705. PerfCounter.Enabled = true;
  9706. return PerfCounter;
  9707. }());
  9708. BABYLON.PerfCounter = PerfCounter;
  9709. /**
  9710. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9711. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9712. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9713. * @param name The name of the class, case should be preserved
  9714. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9715. */
  9716. function className(name, module) {
  9717. return function (target) {
  9718. target["__bjsclassName__"] = name;
  9719. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9720. };
  9721. }
  9722. BABYLON.className = className;
  9723. /**
  9724. * An implementation of a loop for asynchronous functions.
  9725. */
  9726. var AsyncLoop = /** @class */ (function () {
  9727. /**
  9728. * Constroctor.
  9729. * @param iterations the number of iterations.
  9730. * @param _fn the function to run each iteration
  9731. * @param _successCallback the callback that will be called upon succesful execution
  9732. * @param offset starting offset.
  9733. */
  9734. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9735. if (offset === void 0) { offset = 0; }
  9736. this.iterations = iterations;
  9737. this._fn = _fn;
  9738. this._successCallback = _successCallback;
  9739. this.index = offset - 1;
  9740. this._done = false;
  9741. }
  9742. /**
  9743. * Execute the next iteration. Must be called after the last iteration was finished.
  9744. */
  9745. AsyncLoop.prototype.executeNext = function () {
  9746. if (!this._done) {
  9747. if (this.index + 1 < this.iterations) {
  9748. ++this.index;
  9749. this._fn(this);
  9750. }
  9751. else {
  9752. this.breakLoop();
  9753. }
  9754. }
  9755. };
  9756. /**
  9757. * Break the loop and run the success callback.
  9758. */
  9759. AsyncLoop.prototype.breakLoop = function () {
  9760. this._done = true;
  9761. this._successCallback();
  9762. };
  9763. /**
  9764. * Helper function
  9765. */
  9766. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9767. if (offset === void 0) { offset = 0; }
  9768. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9769. loop.executeNext();
  9770. return loop;
  9771. };
  9772. /**
  9773. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9774. * @param iterations total number of iterations
  9775. * @param syncedIterations number of synchronous iterations in each async iteration.
  9776. * @param fn the function to call each iteration.
  9777. * @param callback a success call back that will be called when iterating stops.
  9778. * @param breakFunction a break condition (optional)
  9779. * @param timeout timeout settings for the setTimeout function. default - 0.
  9780. * @constructor
  9781. */
  9782. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9783. if (timeout === void 0) { timeout = 0; }
  9784. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9785. if (breakFunction && breakFunction())
  9786. loop.breakLoop();
  9787. else {
  9788. setTimeout(function () {
  9789. for (var i = 0; i < syncedIterations; ++i) {
  9790. var iteration = (loop.index * syncedIterations) + i;
  9791. if (iteration >= iterations)
  9792. break;
  9793. fn(iteration);
  9794. if (breakFunction && breakFunction()) {
  9795. loop.breakLoop();
  9796. break;
  9797. }
  9798. }
  9799. loop.executeNext();
  9800. }, timeout);
  9801. }
  9802. }, callback);
  9803. };
  9804. return AsyncLoop;
  9805. }());
  9806. BABYLON.AsyncLoop = AsyncLoop;
  9807. })(BABYLON || (BABYLON = {}));
  9808. //# sourceMappingURL=babylon.tools.js.map
  9809. "use strict";
  9810. var BABYLON;
  9811. (function (BABYLON) {
  9812. var PromiseStates;
  9813. (function (PromiseStates) {
  9814. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9815. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9816. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9817. })(PromiseStates || (PromiseStates = {}));
  9818. var FulFillmentAgregator = /** @class */ (function () {
  9819. function FulFillmentAgregator() {
  9820. this.count = 0;
  9821. this.target = 0;
  9822. this.results = [];
  9823. }
  9824. return FulFillmentAgregator;
  9825. }());
  9826. var InternalPromise = /** @class */ (function () {
  9827. function InternalPromise(resolver) {
  9828. var _this = this;
  9829. this._state = PromiseStates.Pending;
  9830. this._children = new Array();
  9831. this._rejectWasConsumed = false;
  9832. if (!resolver) {
  9833. return;
  9834. }
  9835. try {
  9836. resolver(function (value) {
  9837. _this._resolve(value);
  9838. }, function (reason) {
  9839. _this._reject(reason);
  9840. });
  9841. }
  9842. catch (e) {
  9843. this._reject(e);
  9844. }
  9845. }
  9846. InternalPromise.prototype.catch = function (onRejected) {
  9847. return this.then(undefined, onRejected);
  9848. };
  9849. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9850. var _this = this;
  9851. var newPromise = new InternalPromise();
  9852. newPromise._onFulfilled = onFulfilled;
  9853. newPromise._onRejected = onRejected;
  9854. // Composition
  9855. this._children.push(newPromise);
  9856. if (this._state !== PromiseStates.Pending) {
  9857. BABYLON.Tools.SetImmediate(function () {
  9858. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9859. var returnedValue = newPromise._resolve(_this._result);
  9860. if (returnedValue !== undefined && returnedValue !== null) {
  9861. if (returnedValue._state !== undefined) {
  9862. var returnedPromise = returnedValue;
  9863. newPromise._children.push(returnedPromise);
  9864. newPromise = returnedPromise;
  9865. }
  9866. else {
  9867. newPromise._result = returnedValue;
  9868. }
  9869. }
  9870. }
  9871. else {
  9872. newPromise._reject(_this._reason);
  9873. }
  9874. });
  9875. }
  9876. return newPromise;
  9877. };
  9878. InternalPromise.prototype._moveChildren = function (children) {
  9879. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9880. if (this._state === PromiseStates.Fulfilled) {
  9881. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9882. var child = _b[_i];
  9883. child._resolve(this._result);
  9884. }
  9885. }
  9886. else if (this._state === PromiseStates.Rejected) {
  9887. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9888. var child = _d[_c];
  9889. child._reject(this._reason);
  9890. }
  9891. }
  9892. var _a;
  9893. };
  9894. InternalPromise.prototype._resolve = function (value) {
  9895. try {
  9896. this._state = PromiseStates.Fulfilled;
  9897. var returnedValue = null;
  9898. if (this._onFulfilled) {
  9899. returnedValue = this._onFulfilled(value);
  9900. }
  9901. if (returnedValue !== undefined && returnedValue !== null) {
  9902. if (returnedValue._state !== undefined) {
  9903. // Transmit children
  9904. var returnedPromise = returnedValue;
  9905. returnedPromise._moveChildren(this._children);
  9906. value = returnedPromise._result;
  9907. }
  9908. else {
  9909. value = returnedValue;
  9910. }
  9911. }
  9912. this._result = value;
  9913. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9914. var child = _a[_i];
  9915. child._resolve(value);
  9916. }
  9917. this._children.length = 0;
  9918. delete this._onFulfilled;
  9919. delete this._onRejected;
  9920. }
  9921. catch (e) {
  9922. this._reject(e, true);
  9923. }
  9924. };
  9925. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9926. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9927. this._state = PromiseStates.Rejected;
  9928. this._reason = reason;
  9929. if (this._onRejected && !onLocalThrow) {
  9930. try {
  9931. this._onRejected(reason);
  9932. this._rejectWasConsumed = true;
  9933. }
  9934. catch (e) {
  9935. reason = e;
  9936. }
  9937. }
  9938. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9939. var child = _a[_i];
  9940. if (this._rejectWasConsumed) {
  9941. child._resolve(null);
  9942. }
  9943. else {
  9944. child._reject(reason);
  9945. }
  9946. }
  9947. this._children.length = 0;
  9948. delete this._onFulfilled;
  9949. delete this._onRejected;
  9950. };
  9951. InternalPromise.resolve = function (value) {
  9952. var newPromise = new InternalPromise();
  9953. newPromise._resolve(value);
  9954. return newPromise;
  9955. };
  9956. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9957. promise.then(function (value) {
  9958. agregator.results[index] = value;
  9959. agregator.count++;
  9960. if (agregator.count === agregator.target) {
  9961. agregator.rootPromise._resolve(agregator.results);
  9962. }
  9963. return null;
  9964. }, function (reason) {
  9965. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9966. agregator.rootPromise._reject(reason);
  9967. }
  9968. });
  9969. };
  9970. InternalPromise.all = function (promises) {
  9971. var newPromise = new InternalPromise();
  9972. var agregator = new FulFillmentAgregator();
  9973. agregator.target = promises.length;
  9974. agregator.rootPromise = newPromise;
  9975. if (promises.length) {
  9976. for (var index = 0; index < promises.length; index++) {
  9977. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9978. }
  9979. }
  9980. else {
  9981. newPromise._resolve([]);
  9982. }
  9983. return newPromise;
  9984. };
  9985. InternalPromise.race = function (promises) {
  9986. var newPromise = new InternalPromise();
  9987. if (promises.length) {
  9988. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9989. var promise = promises_1[_i];
  9990. promise.then(function (value) {
  9991. if (newPromise) {
  9992. newPromise._resolve(value);
  9993. newPromise = null;
  9994. }
  9995. return null;
  9996. }, function (reason) {
  9997. if (newPromise) {
  9998. newPromise._reject(reason);
  9999. newPromise = null;
  10000. }
  10001. });
  10002. }
  10003. }
  10004. return newPromise;
  10005. };
  10006. return InternalPromise;
  10007. }());
  10008. /**
  10009. * Helper class that provides a small promise polyfill
  10010. */
  10011. var PromisePolyfill = /** @class */ (function () {
  10012. function PromisePolyfill() {
  10013. }
  10014. /**
  10015. * Static function used to check if the polyfill is required
  10016. * If this is the case then the function will inject the polyfill to window.Promise
  10017. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10018. */
  10019. PromisePolyfill.Apply = function (force) {
  10020. if (force === void 0) { force = false; }
  10021. if (force || typeof Promise === 'undefined') {
  10022. var root = window;
  10023. root.Promise = InternalPromise;
  10024. }
  10025. };
  10026. return PromisePolyfill;
  10027. }());
  10028. BABYLON.PromisePolyfill = PromisePolyfill;
  10029. })(BABYLON || (BABYLON = {}));
  10030. //# sourceMappingURL=babylon.promise.js.map
  10031. "use strict";
  10032. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10033. var BABYLON;
  10034. (function (BABYLON) {
  10035. /**
  10036. * Helper class to push actions to a pool of workers.
  10037. */
  10038. var WorkerPool = /** @class */ (function () {
  10039. /**
  10040. * Constructor
  10041. * @param workers Array of workers to use for actions
  10042. */
  10043. function WorkerPool(workers) {
  10044. this._pendingActions = new Array();
  10045. this._workerInfos = workers.map(function (worker) { return ({
  10046. worker: worker,
  10047. active: false
  10048. }); });
  10049. }
  10050. /**
  10051. * Terminates all workers and clears any pending actions.
  10052. */
  10053. WorkerPool.prototype.dispose = function () {
  10054. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10055. var workerInfo = _a[_i];
  10056. workerInfo.worker.terminate();
  10057. }
  10058. delete this._workerInfos;
  10059. delete this._pendingActions;
  10060. };
  10061. /**
  10062. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10063. * pended until a worker has completed its action.
  10064. * @param action The action to perform. Call onComplete when the action is complete.
  10065. */
  10066. WorkerPool.prototype.push = function (action) {
  10067. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10068. var workerInfo = _a[_i];
  10069. if (!workerInfo.active) {
  10070. this._execute(workerInfo, action);
  10071. return;
  10072. }
  10073. }
  10074. this._pendingActions.push(action);
  10075. };
  10076. WorkerPool.prototype._execute = function (workerInfo, action) {
  10077. var _this = this;
  10078. workerInfo.active = true;
  10079. action(workerInfo.worker, function () {
  10080. workerInfo.active = false;
  10081. var nextAction = _this._pendingActions.shift();
  10082. if (nextAction) {
  10083. _this._execute(workerInfo, nextAction);
  10084. }
  10085. });
  10086. };
  10087. return WorkerPool;
  10088. }());
  10089. BABYLON.WorkerPool = WorkerPool;
  10090. })(BABYLON || (BABYLON = {}));
  10091. //# sourceMappingURL=babylon.workerPool.js.map
  10092. "use strict";
  10093. var BABYLON;
  10094. (function (BABYLON) {
  10095. var _AlphaState = /** @class */ (function () {
  10096. /**
  10097. * Initializes the state.
  10098. */
  10099. function _AlphaState() {
  10100. this._isAlphaBlendDirty = false;
  10101. this._isBlendFunctionParametersDirty = false;
  10102. this._isBlendEquationParametersDirty = false;
  10103. this._isBlendConstantsDirty = false;
  10104. this._alphaBlend = false;
  10105. this._blendFunctionParameters = new Array(4);
  10106. this._blendEquationParameters = new Array(2);
  10107. this._blendConstants = new Array(4);
  10108. this.reset();
  10109. }
  10110. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10111. get: function () {
  10112. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10113. },
  10114. enumerable: true,
  10115. configurable: true
  10116. });
  10117. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10118. get: function () {
  10119. return this._alphaBlend;
  10120. },
  10121. set: function (value) {
  10122. if (this._alphaBlend === value) {
  10123. return;
  10124. }
  10125. this._alphaBlend = value;
  10126. this._isAlphaBlendDirty = true;
  10127. },
  10128. enumerable: true,
  10129. configurable: true
  10130. });
  10131. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10132. if (this._blendConstants[0] === r &&
  10133. this._blendConstants[1] === g &&
  10134. this._blendConstants[2] === b &&
  10135. this._blendConstants[3] === a) {
  10136. return;
  10137. }
  10138. this._blendConstants[0] = r;
  10139. this._blendConstants[1] = g;
  10140. this._blendConstants[2] = b;
  10141. this._blendConstants[3] = a;
  10142. this._isBlendConstantsDirty = true;
  10143. };
  10144. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10145. if (this._blendFunctionParameters[0] === value0 &&
  10146. this._blendFunctionParameters[1] === value1 &&
  10147. this._blendFunctionParameters[2] === value2 &&
  10148. this._blendFunctionParameters[3] === value3) {
  10149. return;
  10150. }
  10151. this._blendFunctionParameters[0] = value0;
  10152. this._blendFunctionParameters[1] = value1;
  10153. this._blendFunctionParameters[2] = value2;
  10154. this._blendFunctionParameters[3] = value3;
  10155. this._isBlendFunctionParametersDirty = true;
  10156. };
  10157. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10158. if (this._blendEquationParameters[0] === rgb &&
  10159. this._blendEquationParameters[1] === alpha) {
  10160. return;
  10161. }
  10162. this._blendEquationParameters[0] = rgb;
  10163. this._blendEquationParameters[1] = alpha;
  10164. this._isBlendEquationParametersDirty = true;
  10165. };
  10166. _AlphaState.prototype.reset = function () {
  10167. this._alphaBlend = false;
  10168. this._blendFunctionParameters[0] = null;
  10169. this._blendFunctionParameters[1] = null;
  10170. this._blendFunctionParameters[2] = null;
  10171. this._blendFunctionParameters[3] = null;
  10172. this._blendEquationParameters[0] = null;
  10173. this._blendEquationParameters[1] = null;
  10174. this._blendConstants[0] = null;
  10175. this._blendConstants[1] = null;
  10176. this._blendConstants[2] = null;
  10177. this._blendConstants[3] = null;
  10178. this._isAlphaBlendDirty = true;
  10179. this._isBlendFunctionParametersDirty = false;
  10180. this._isBlendEquationParametersDirty = false;
  10181. this._isBlendConstantsDirty = false;
  10182. };
  10183. _AlphaState.prototype.apply = function (gl) {
  10184. if (!this.isDirty) {
  10185. return;
  10186. }
  10187. // Alpha blend
  10188. if (this._isAlphaBlendDirty) {
  10189. if (this._alphaBlend) {
  10190. gl.enable(gl.BLEND);
  10191. }
  10192. else {
  10193. gl.disable(gl.BLEND);
  10194. }
  10195. this._isAlphaBlendDirty = false;
  10196. }
  10197. // Alpha function
  10198. if (this._isBlendFunctionParametersDirty) {
  10199. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10200. this._isBlendFunctionParametersDirty = false;
  10201. }
  10202. // Alpha equation
  10203. if (this._isBlendEquationParametersDirty) {
  10204. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10205. this._isBlendEquationParametersDirty = false;
  10206. }
  10207. // Constants
  10208. if (this._isBlendConstantsDirty) {
  10209. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10210. this._isBlendConstantsDirty = false;
  10211. }
  10212. };
  10213. return _AlphaState;
  10214. }());
  10215. BABYLON._AlphaState = _AlphaState;
  10216. })(BABYLON || (BABYLON = {}));
  10217. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10218. "use strict";
  10219. var BABYLON;
  10220. (function (BABYLON) {
  10221. var _DepthCullingState = /** @class */ (function () {
  10222. /**
  10223. * Initializes the state.
  10224. */
  10225. function _DepthCullingState() {
  10226. this._isDepthTestDirty = false;
  10227. this._isDepthMaskDirty = false;
  10228. this._isDepthFuncDirty = false;
  10229. this._isCullFaceDirty = false;
  10230. this._isCullDirty = false;
  10231. this._isZOffsetDirty = false;
  10232. this._isFrontFaceDirty = false;
  10233. this.reset();
  10234. }
  10235. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10236. get: function () {
  10237. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10238. },
  10239. enumerable: true,
  10240. configurable: true
  10241. });
  10242. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10243. get: function () {
  10244. return this._zOffset;
  10245. },
  10246. set: function (value) {
  10247. if (this._zOffset === value) {
  10248. return;
  10249. }
  10250. this._zOffset = value;
  10251. this._isZOffsetDirty = true;
  10252. },
  10253. enumerable: true,
  10254. configurable: true
  10255. });
  10256. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10257. get: function () {
  10258. return this._cullFace;
  10259. },
  10260. set: function (value) {
  10261. if (this._cullFace === value) {
  10262. return;
  10263. }
  10264. this._cullFace = value;
  10265. this._isCullFaceDirty = true;
  10266. },
  10267. enumerable: true,
  10268. configurable: true
  10269. });
  10270. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10271. get: function () {
  10272. return this._cull;
  10273. },
  10274. set: function (value) {
  10275. if (this._cull === value) {
  10276. return;
  10277. }
  10278. this._cull = value;
  10279. this._isCullDirty = true;
  10280. },
  10281. enumerable: true,
  10282. configurable: true
  10283. });
  10284. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10285. get: function () {
  10286. return this._depthFunc;
  10287. },
  10288. set: function (value) {
  10289. if (this._depthFunc === value) {
  10290. return;
  10291. }
  10292. this._depthFunc = value;
  10293. this._isDepthFuncDirty = true;
  10294. },
  10295. enumerable: true,
  10296. configurable: true
  10297. });
  10298. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10299. get: function () {
  10300. return this._depthMask;
  10301. },
  10302. set: function (value) {
  10303. if (this._depthMask === value) {
  10304. return;
  10305. }
  10306. this._depthMask = value;
  10307. this._isDepthMaskDirty = true;
  10308. },
  10309. enumerable: true,
  10310. configurable: true
  10311. });
  10312. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10313. get: function () {
  10314. return this._depthTest;
  10315. },
  10316. set: function (value) {
  10317. if (this._depthTest === value) {
  10318. return;
  10319. }
  10320. this._depthTest = value;
  10321. this._isDepthTestDirty = true;
  10322. },
  10323. enumerable: true,
  10324. configurable: true
  10325. });
  10326. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10327. get: function () {
  10328. return this._frontFace;
  10329. },
  10330. set: function (value) {
  10331. if (this._frontFace === value) {
  10332. return;
  10333. }
  10334. this._frontFace = value;
  10335. this._isFrontFaceDirty = true;
  10336. },
  10337. enumerable: true,
  10338. configurable: true
  10339. });
  10340. _DepthCullingState.prototype.reset = function () {
  10341. this._depthMask = true;
  10342. this._depthTest = true;
  10343. this._depthFunc = null;
  10344. this._cullFace = null;
  10345. this._cull = null;
  10346. this._zOffset = 0;
  10347. this._frontFace = null;
  10348. this._isDepthTestDirty = true;
  10349. this._isDepthMaskDirty = true;
  10350. this._isDepthFuncDirty = false;
  10351. this._isCullFaceDirty = false;
  10352. this._isCullDirty = false;
  10353. this._isZOffsetDirty = false;
  10354. this._isFrontFaceDirty = false;
  10355. };
  10356. _DepthCullingState.prototype.apply = function (gl) {
  10357. if (!this.isDirty) {
  10358. return;
  10359. }
  10360. // Cull
  10361. if (this._isCullDirty) {
  10362. if (this.cull) {
  10363. gl.enable(gl.CULL_FACE);
  10364. }
  10365. else {
  10366. gl.disable(gl.CULL_FACE);
  10367. }
  10368. this._isCullDirty = false;
  10369. }
  10370. // Cull face
  10371. if (this._isCullFaceDirty) {
  10372. gl.cullFace(this.cullFace);
  10373. this._isCullFaceDirty = false;
  10374. }
  10375. // Depth mask
  10376. if (this._isDepthMaskDirty) {
  10377. gl.depthMask(this.depthMask);
  10378. this._isDepthMaskDirty = false;
  10379. }
  10380. // Depth test
  10381. if (this._isDepthTestDirty) {
  10382. if (this.depthTest) {
  10383. gl.enable(gl.DEPTH_TEST);
  10384. }
  10385. else {
  10386. gl.disable(gl.DEPTH_TEST);
  10387. }
  10388. this._isDepthTestDirty = false;
  10389. }
  10390. // Depth func
  10391. if (this._isDepthFuncDirty) {
  10392. gl.depthFunc(this.depthFunc);
  10393. this._isDepthFuncDirty = false;
  10394. }
  10395. // zOffset
  10396. if (this._isZOffsetDirty) {
  10397. if (this.zOffset) {
  10398. gl.enable(gl.POLYGON_OFFSET_FILL);
  10399. gl.polygonOffset(this.zOffset, 0);
  10400. }
  10401. else {
  10402. gl.disable(gl.POLYGON_OFFSET_FILL);
  10403. }
  10404. this._isZOffsetDirty = false;
  10405. }
  10406. // Front face
  10407. if (this._isFrontFaceDirty) {
  10408. gl.frontFace(this.frontFace);
  10409. this._isFrontFaceDirty = false;
  10410. }
  10411. };
  10412. return _DepthCullingState;
  10413. }());
  10414. BABYLON._DepthCullingState = _DepthCullingState;
  10415. })(BABYLON || (BABYLON = {}));
  10416. //# sourceMappingURL=babylon.depthCullingState.js.map
  10417. "use strict";
  10418. var BABYLON;
  10419. (function (BABYLON) {
  10420. var _StencilState = /** @class */ (function () {
  10421. function _StencilState() {
  10422. this._isStencilTestDirty = false;
  10423. this._isStencilMaskDirty = false;
  10424. this._isStencilFuncDirty = false;
  10425. this._isStencilOpDirty = false;
  10426. this.reset();
  10427. }
  10428. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10429. get: function () {
  10430. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10431. },
  10432. enumerable: true,
  10433. configurable: true
  10434. });
  10435. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10436. get: function () {
  10437. return this._stencilFunc;
  10438. },
  10439. set: function (value) {
  10440. if (this._stencilFunc === value) {
  10441. return;
  10442. }
  10443. this._stencilFunc = value;
  10444. this._isStencilFuncDirty = true;
  10445. },
  10446. enumerable: true,
  10447. configurable: true
  10448. });
  10449. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10450. get: function () {
  10451. return this._stencilFuncRef;
  10452. },
  10453. set: function (value) {
  10454. if (this._stencilFuncRef === value) {
  10455. return;
  10456. }
  10457. this._stencilFuncRef = value;
  10458. this._isStencilFuncDirty = true;
  10459. },
  10460. enumerable: true,
  10461. configurable: true
  10462. });
  10463. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10464. get: function () {
  10465. return this._stencilFuncMask;
  10466. },
  10467. set: function (value) {
  10468. if (this._stencilFuncMask === value) {
  10469. return;
  10470. }
  10471. this._stencilFuncMask = value;
  10472. this._isStencilFuncDirty = true;
  10473. },
  10474. enumerable: true,
  10475. configurable: true
  10476. });
  10477. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10478. get: function () {
  10479. return this._stencilOpStencilFail;
  10480. },
  10481. set: function (value) {
  10482. if (this._stencilOpStencilFail === value) {
  10483. return;
  10484. }
  10485. this._stencilOpStencilFail = value;
  10486. this._isStencilOpDirty = true;
  10487. },
  10488. enumerable: true,
  10489. configurable: true
  10490. });
  10491. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10492. get: function () {
  10493. return this._stencilOpDepthFail;
  10494. },
  10495. set: function (value) {
  10496. if (this._stencilOpDepthFail === value) {
  10497. return;
  10498. }
  10499. this._stencilOpDepthFail = value;
  10500. this._isStencilOpDirty = true;
  10501. },
  10502. enumerable: true,
  10503. configurable: true
  10504. });
  10505. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10506. get: function () {
  10507. return this._stencilOpStencilDepthPass;
  10508. },
  10509. set: function (value) {
  10510. if (this._stencilOpStencilDepthPass === value) {
  10511. return;
  10512. }
  10513. this._stencilOpStencilDepthPass = value;
  10514. this._isStencilOpDirty = true;
  10515. },
  10516. enumerable: true,
  10517. configurable: true
  10518. });
  10519. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10520. get: function () {
  10521. return this._stencilMask;
  10522. },
  10523. set: function (value) {
  10524. if (this._stencilMask === value) {
  10525. return;
  10526. }
  10527. this._stencilMask = value;
  10528. this._isStencilMaskDirty = true;
  10529. },
  10530. enumerable: true,
  10531. configurable: true
  10532. });
  10533. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10534. get: function () {
  10535. return this._stencilTest;
  10536. },
  10537. set: function (value) {
  10538. if (this._stencilTest === value) {
  10539. return;
  10540. }
  10541. this._stencilTest = value;
  10542. this._isStencilTestDirty = true;
  10543. },
  10544. enumerable: true,
  10545. configurable: true
  10546. });
  10547. _StencilState.prototype.reset = function () {
  10548. this._stencilTest = false;
  10549. this._stencilMask = 0xFF;
  10550. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10551. this._stencilFuncRef = 1;
  10552. this._stencilFuncMask = 0xFF;
  10553. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10554. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10555. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10556. this._isStencilTestDirty = true;
  10557. this._isStencilMaskDirty = true;
  10558. this._isStencilFuncDirty = true;
  10559. this._isStencilOpDirty = true;
  10560. };
  10561. _StencilState.prototype.apply = function (gl) {
  10562. if (!this.isDirty) {
  10563. return;
  10564. }
  10565. // Stencil test
  10566. if (this._isStencilTestDirty) {
  10567. if (this.stencilTest) {
  10568. gl.enable(gl.STENCIL_TEST);
  10569. }
  10570. else {
  10571. gl.disable(gl.STENCIL_TEST);
  10572. }
  10573. this._isStencilTestDirty = false;
  10574. }
  10575. // Stencil mask
  10576. if (this._isStencilMaskDirty) {
  10577. gl.stencilMask(this.stencilMask);
  10578. this._isStencilMaskDirty = false;
  10579. }
  10580. // Stencil func
  10581. if (this._isStencilFuncDirty) {
  10582. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10583. this._isStencilFuncDirty = false;
  10584. }
  10585. // Stencil op
  10586. if (this._isStencilOpDirty) {
  10587. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10588. this._isStencilOpDirty = false;
  10589. }
  10590. };
  10591. return _StencilState;
  10592. }());
  10593. BABYLON._StencilState = _StencilState;
  10594. })(BABYLON || (BABYLON = {}));
  10595. //# sourceMappingURL=babylon.stencilState.js.map
  10596. "use strict";
  10597. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10598. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10599. s = arguments[i];
  10600. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10601. t[p] = s[p];
  10602. }
  10603. return t;
  10604. };
  10605. var BABYLON;
  10606. (function (BABYLON) {
  10607. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10608. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10609. };
  10610. var compileRawShader = function (gl, source, type) {
  10611. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10612. gl.shaderSource(shader, source);
  10613. gl.compileShader(shader);
  10614. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10615. var log = gl.getShaderInfoLog(shader);
  10616. if (log) {
  10617. throw new Error(log);
  10618. }
  10619. }
  10620. if (!shader) {
  10621. throw new Error("Something went wrong while compile the shader.");
  10622. }
  10623. return shader;
  10624. };
  10625. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10626. var magFilter = gl.NEAREST;
  10627. var minFilter = gl.NEAREST;
  10628. switch (samplingMode) {
  10629. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10630. magFilter = gl.LINEAR;
  10631. if (generateMipMaps) {
  10632. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10633. }
  10634. else {
  10635. minFilter = gl.LINEAR;
  10636. }
  10637. break;
  10638. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10639. magFilter = gl.LINEAR;
  10640. if (generateMipMaps) {
  10641. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10642. }
  10643. else {
  10644. minFilter = gl.LINEAR;
  10645. }
  10646. break;
  10647. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10648. magFilter = gl.NEAREST;
  10649. if (generateMipMaps) {
  10650. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10651. }
  10652. else {
  10653. minFilter = gl.NEAREST;
  10654. }
  10655. break;
  10656. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10657. magFilter = gl.NEAREST;
  10658. if (generateMipMaps) {
  10659. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10660. }
  10661. else {
  10662. minFilter = gl.NEAREST;
  10663. }
  10664. break;
  10665. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10666. magFilter = gl.NEAREST;
  10667. if (generateMipMaps) {
  10668. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10669. }
  10670. else {
  10671. minFilter = gl.LINEAR;
  10672. }
  10673. break;
  10674. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10675. magFilter = gl.NEAREST;
  10676. if (generateMipMaps) {
  10677. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10678. }
  10679. else {
  10680. minFilter = gl.LINEAR;
  10681. }
  10682. break;
  10683. case BABYLON.Texture.NEAREST_LINEAR:
  10684. magFilter = gl.NEAREST;
  10685. minFilter = gl.LINEAR;
  10686. break;
  10687. case BABYLON.Texture.NEAREST_NEAREST:
  10688. magFilter = gl.NEAREST;
  10689. minFilter = gl.NEAREST;
  10690. break;
  10691. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10692. magFilter = gl.LINEAR;
  10693. if (generateMipMaps) {
  10694. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10695. }
  10696. else {
  10697. minFilter = gl.NEAREST;
  10698. }
  10699. break;
  10700. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10701. magFilter = gl.LINEAR;
  10702. if (generateMipMaps) {
  10703. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10704. }
  10705. else {
  10706. minFilter = gl.NEAREST;
  10707. }
  10708. break;
  10709. case BABYLON.Texture.LINEAR_LINEAR:
  10710. magFilter = gl.LINEAR;
  10711. minFilter = gl.LINEAR;
  10712. break;
  10713. case BABYLON.Texture.LINEAR_NEAREST:
  10714. magFilter = gl.LINEAR;
  10715. minFilter = gl.NEAREST;
  10716. break;
  10717. }
  10718. return {
  10719. min: minFilter,
  10720. mag: magFilter
  10721. };
  10722. };
  10723. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10724. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10725. var img;
  10726. var onload = function () {
  10727. loadedImages[index] = img;
  10728. loadedImages._internalCount++;
  10729. if (scene) {
  10730. scene._removePendingData(img);
  10731. }
  10732. if (loadedImages._internalCount === 6) {
  10733. onfinish(loadedImages);
  10734. }
  10735. };
  10736. var onerror = function (message, exception) {
  10737. if (scene) {
  10738. scene._removePendingData(img);
  10739. }
  10740. if (onErrorCallBack) {
  10741. onErrorCallBack(message, exception);
  10742. }
  10743. };
  10744. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10745. if (scene) {
  10746. scene._addPendingData(img);
  10747. }
  10748. };
  10749. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10750. if (onError === void 0) { onError = null; }
  10751. var loadedImages = [];
  10752. loadedImages._internalCount = 0;
  10753. for (var index = 0; index < 6; index++) {
  10754. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10755. }
  10756. };
  10757. var BufferPointer = /** @class */ (function () {
  10758. function BufferPointer() {
  10759. }
  10760. return BufferPointer;
  10761. }());
  10762. /**
  10763. * Interface for attribute information associated with buffer instanciation
  10764. */
  10765. var InstancingAttributeInfo = /** @class */ (function () {
  10766. function InstancingAttributeInfo() {
  10767. }
  10768. return InstancingAttributeInfo;
  10769. }());
  10770. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10771. /**
  10772. * Define options used to create a render target texture
  10773. */
  10774. var RenderTargetCreationOptions = /** @class */ (function () {
  10775. function RenderTargetCreationOptions() {
  10776. }
  10777. return RenderTargetCreationOptions;
  10778. }());
  10779. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10780. /**
  10781. * Define options used to create a depth texture
  10782. */
  10783. var DepthTextureCreationOptions = /** @class */ (function () {
  10784. function DepthTextureCreationOptions() {
  10785. }
  10786. return DepthTextureCreationOptions;
  10787. }());
  10788. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10789. /**
  10790. * Class used to describe the capabilities of the engine relatively to the current browser
  10791. */
  10792. var EngineCapabilities = /** @class */ (function () {
  10793. function EngineCapabilities() {
  10794. }
  10795. return EngineCapabilities;
  10796. }());
  10797. BABYLON.EngineCapabilities = EngineCapabilities;
  10798. /**
  10799. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  10800. */
  10801. var Engine = /** @class */ (function () {
  10802. /**
  10803. * Creates a new engine
  10804. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10805. * @param antialias defines enable antialiasing (default: false)
  10806. * @param options defines further options to be sent to the getContext() function
  10807. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10808. */
  10809. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10810. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10811. var _this = this;
  10812. // Public members
  10813. /**
  10814. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  10815. */
  10816. this.forcePOTTextures = false;
  10817. /**
  10818. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  10819. */
  10820. this.isFullscreen = false;
  10821. /**
  10822. * Gets a boolean indicating if the pointer is currently locked
  10823. */
  10824. this.isPointerLock = false;
  10825. /**
  10826. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  10827. */
  10828. this.cullBackFaces = true;
  10829. /**
  10830. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  10831. */
  10832. this.renderEvenInBackground = true;
  10833. /**
  10834. * Gets or sets a boolean indicating that cache can be kept between frames
  10835. */
  10836. this.preventCacheWipeBetweenFrames = false;
  10837. /**
  10838. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  10839. **/
  10840. this.enableOfflineSupport = false;
  10841. /**
  10842. * Gets the list of created scenes
  10843. */
  10844. this.scenes = new Array();
  10845. /**
  10846. * Gets the list of created postprocesses
  10847. */
  10848. this.postProcesses = new Array();
  10849. // Observables
  10850. /**
  10851. * Observable event triggered each time the rendering canvas is resized
  10852. */
  10853. this.onResizeObservable = new BABYLON.Observable();
  10854. /**
  10855. * Observable event triggered each time the canvas loses focus
  10856. */
  10857. this.onCanvasBlurObservable = new BABYLON.Observable();
  10858. /**
  10859. * Observable event triggered each time the canvas gains focus
  10860. */
  10861. this.onCanvasFocusObservable = new BABYLON.Observable();
  10862. /**
  10863. * Observable event triggered each time the canvas receives pointerout event
  10864. */
  10865. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10866. /**
  10867. * Observable event triggered before each texture is initialized
  10868. */
  10869. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10870. //WebVR
  10871. this._vrDisplay = undefined;
  10872. this._vrSupported = false;
  10873. this._vrExclusivePointerMode = false;
  10874. // Uniform buffers list
  10875. /**
  10876. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  10877. */
  10878. this.disableUniformBuffers = false;
  10879. /** @ignore */
  10880. this._uniformBuffers = new Array();
  10881. // Observables
  10882. /**
  10883. * Observable raised when the engine begins a new frame
  10884. */
  10885. this.onBeginFrameObservable = new BABYLON.Observable();
  10886. /**
  10887. * Observable raised when the engine ends the current frame
  10888. */
  10889. this.onEndFrameObservable = new BABYLON.Observable();
  10890. /**
  10891. * Observable raised when the engine is about to compile a shader
  10892. */
  10893. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10894. /**
  10895. * Observable raised when the engine has jsut compiled a shader
  10896. */
  10897. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10898. this._windowIsBackground = false;
  10899. this._webGLVersion = 1.0;
  10900. /** @ignore */
  10901. this._badOS = false;
  10902. /** @ignore */
  10903. this._badDesktopOS = false;
  10904. /**
  10905. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10906. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  10907. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  10908. */
  10909. this.disableTextureBindingOptimization = false;
  10910. /**
  10911. * Observable signaled when VR display mode changes
  10912. */
  10913. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10914. /**
  10915. * Observable signaled when VR request present is complete
  10916. */
  10917. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10918. /**
  10919. * Observable signaled when VR request present starts
  10920. */
  10921. this.onVRRequestPresentStart = new BABYLON.Observable();
  10922. this._colorWrite = true;
  10923. /** @ignore */
  10924. this._drawCalls = new BABYLON.PerfCounter();
  10925. /** @ignore */
  10926. this._textureCollisions = new BABYLON.PerfCounter();
  10927. this._renderingQueueLaunched = false;
  10928. this._activeRenderLoops = new Array();
  10929. // Deterministic lockstepMaxSteps
  10930. this._deterministicLockstep = false;
  10931. this._lockstepMaxSteps = 4;
  10932. // Lost context
  10933. /**
  10934. * Observable signaled when a context lost event is raised
  10935. */
  10936. this.onContextLostObservable = new BABYLON.Observable();
  10937. /**
  10938. * Observable signaled when a context restored event is raised
  10939. */
  10940. this.onContextRestoredObservable = new BABYLON.Observable();
  10941. this._contextWasLost = false;
  10942. this._doNotHandleContextLost = false;
  10943. // FPS
  10944. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10945. this._fps = 60;
  10946. this._deltaTime = 0;
  10947. /**
  10948. * Turn this value on if you want to pause FPS computation when in background
  10949. */
  10950. this.disablePerformanceMonitorInBackground = false;
  10951. // States
  10952. /** @ignore */
  10953. this._depthCullingState = new BABYLON._DepthCullingState();
  10954. /** @ignore */
  10955. this._stencilState = new BABYLON._StencilState();
  10956. /** @ignore */
  10957. this._alphaState = new BABYLON._AlphaState();
  10958. /** @ignore */
  10959. this._alphaMode = Engine.ALPHA_DISABLE;
  10960. // Cache
  10961. this._internalTexturesCache = new Array();
  10962. /** @ignore */
  10963. this._activeChannel = 0;
  10964. this._currentTextureChannel = -1;
  10965. /** @ignore */
  10966. this._boundTexturesCache = {};
  10967. this._compiledEffects = {};
  10968. this._vertexAttribArraysEnabled = [];
  10969. this._uintIndicesCurrentlySet = false;
  10970. this._currentBoundBuffer = new Array();
  10971. this._currentBufferPointers = new Array();
  10972. this._currentInstanceLocations = new Array();
  10973. this._currentInstanceBuffers = new Array();
  10974. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10975. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10976. this._vaoRecordInProgress = false;
  10977. this._mustWipeVertexAttributes = false;
  10978. this._nextFreeTextureSlots = new Array();
  10979. this._maxSimultaneousTextures = 0;
  10980. this._activeRequests = new Array();
  10981. // Hardware supported Compressed Textures
  10982. this._texturesSupported = new Array();
  10983. this._onVRFullScreenTriggered = function () {
  10984. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10985. //get the old size before we change
  10986. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10987. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10988. //get the width and height, change the render size
  10989. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10990. _this.setHardwareScalingLevel(1);
  10991. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10992. }
  10993. else {
  10994. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10995. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10996. }
  10997. };
  10998. this._boundUniforms = {};
  10999. // Register promises
  11000. BABYLON.PromisePolyfill.Apply();
  11001. var canvas = null;
  11002. Engine.Instances.push(this);
  11003. if (!canvasOrContext) {
  11004. return;
  11005. }
  11006. options = options || {};
  11007. if (canvasOrContext.getContext) {
  11008. canvas = canvasOrContext;
  11009. this._renderingCanvas = canvas;
  11010. if (antialias != null) {
  11011. options.antialias = antialias;
  11012. }
  11013. if (options.deterministicLockstep === undefined) {
  11014. options.deterministicLockstep = false;
  11015. }
  11016. if (options.lockstepMaxSteps === undefined) {
  11017. options.lockstepMaxSteps = 4;
  11018. }
  11019. if (options.preserveDrawingBuffer === undefined) {
  11020. options.preserveDrawingBuffer = false;
  11021. }
  11022. if (options.audioEngine === undefined) {
  11023. options.audioEngine = true;
  11024. }
  11025. if (options.stencil === undefined) {
  11026. options.stencil = true;
  11027. }
  11028. this._deterministicLockstep = options.deterministicLockstep;
  11029. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11030. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11031. // Exceptions
  11032. if (navigator && navigator.userAgent) {
  11033. var ua = navigator.userAgent;
  11034. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11035. var exception = _a[_i];
  11036. var key = exception.key;
  11037. var targets = exception.targets;
  11038. if (ua.indexOf(key) > -1) {
  11039. if (exception.capture && exception.captureConstraint) {
  11040. var capture = exception.capture;
  11041. var constraint = exception.captureConstraint;
  11042. var regex = new RegExp(capture);
  11043. var matches = regex.exec(ua);
  11044. if (matches && matches.length > 0) {
  11045. var capturedValue = parseInt(matches[matches.length - 1]);
  11046. if (capturedValue >= constraint) {
  11047. continue;
  11048. }
  11049. }
  11050. }
  11051. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11052. var target = targets_1[_b];
  11053. switch (target) {
  11054. case "uniformBuffer":
  11055. this.disableUniformBuffers = true;
  11056. break;
  11057. case "textureBindingOptimization":
  11058. this.disableTextureBindingOptimization = true;
  11059. break;
  11060. }
  11061. }
  11062. }
  11063. }
  11064. }
  11065. // GL
  11066. if (!options.disableWebGL2Support) {
  11067. try {
  11068. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11069. if (this._gl) {
  11070. this._webGLVersion = 2.0;
  11071. }
  11072. }
  11073. catch (e) {
  11074. // Do nothing
  11075. }
  11076. }
  11077. if (!this._gl) {
  11078. if (!canvas) {
  11079. throw new Error("The provided canvas is null or undefined.");
  11080. }
  11081. try {
  11082. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11083. }
  11084. catch (e) {
  11085. throw new Error("WebGL not supported");
  11086. }
  11087. }
  11088. if (!this._gl) {
  11089. throw new Error("WebGL not supported");
  11090. }
  11091. this._onCanvasFocus = function () {
  11092. _this.onCanvasFocusObservable.notifyObservers(_this);
  11093. };
  11094. this._onCanvasBlur = function () {
  11095. _this.onCanvasBlurObservable.notifyObservers(_this);
  11096. };
  11097. canvas.addEventListener("focus", this._onCanvasFocus);
  11098. canvas.addEventListener("blur", this._onCanvasBlur);
  11099. this._onBlur = function () {
  11100. if (_this.disablePerformanceMonitorInBackground) {
  11101. _this._performanceMonitor.disable();
  11102. }
  11103. _this._windowIsBackground = true;
  11104. };
  11105. this._onFocus = function () {
  11106. if (_this.disablePerformanceMonitorInBackground) {
  11107. _this._performanceMonitor.enable();
  11108. }
  11109. _this._windowIsBackground = false;
  11110. };
  11111. this._onCanvasPointerOut = function (ev) {
  11112. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11113. };
  11114. window.addEventListener("blur", this._onBlur);
  11115. window.addEventListener("focus", this._onFocus);
  11116. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11117. // Context lost
  11118. if (!this._doNotHandleContextLost) {
  11119. this._onContextLost = function (evt) {
  11120. evt.preventDefault();
  11121. _this._contextWasLost = true;
  11122. BABYLON.Tools.Warn("WebGL context lost.");
  11123. _this.onContextLostObservable.notifyObservers(_this);
  11124. };
  11125. this._onContextRestored = function (evt) {
  11126. // Adding a timeout to avoid race condition at browser level
  11127. setTimeout(function () {
  11128. // Rebuild gl context
  11129. _this._initGLContext();
  11130. // Rebuild effects
  11131. _this._rebuildEffects();
  11132. // Rebuild textures
  11133. _this._rebuildInternalTextures();
  11134. // Rebuild buffers
  11135. _this._rebuildBuffers();
  11136. // Cache
  11137. _this.wipeCaches(true);
  11138. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11139. _this.onContextRestoredObservable.notifyObservers(_this);
  11140. _this._contextWasLost = false;
  11141. }, 0);
  11142. };
  11143. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11144. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11145. }
  11146. }
  11147. else {
  11148. this._gl = canvasOrContext;
  11149. this._renderingCanvas = this._gl.canvas;
  11150. if (this._gl.renderbufferStorageMultisample) {
  11151. this._webGLVersion = 2.0;
  11152. }
  11153. options.stencil = this._gl.getContextAttributes().stencil;
  11154. }
  11155. // Viewport
  11156. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11157. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11158. this.resize();
  11159. this._isStencilEnable = options.stencil ? true : false;
  11160. this._initGLContext();
  11161. if (canvas) {
  11162. // Fullscreen
  11163. this._onFullscreenChange = function () {
  11164. if (document.fullscreen !== undefined) {
  11165. _this.isFullscreen = document.fullscreen;
  11166. }
  11167. else if (document.mozFullScreen !== undefined) {
  11168. _this.isFullscreen = document.mozFullScreen;
  11169. }
  11170. else if (document.webkitIsFullScreen !== undefined) {
  11171. _this.isFullscreen = document.webkitIsFullScreen;
  11172. }
  11173. else if (document.msIsFullScreen !== undefined) {
  11174. _this.isFullscreen = document.msIsFullScreen;
  11175. }
  11176. // Pointer lock
  11177. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11178. canvas.requestPointerLock = canvas.requestPointerLock ||
  11179. canvas.msRequestPointerLock ||
  11180. canvas.mozRequestPointerLock ||
  11181. canvas.webkitRequestPointerLock;
  11182. if (canvas.requestPointerLock) {
  11183. canvas.requestPointerLock();
  11184. }
  11185. }
  11186. };
  11187. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11188. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11189. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11190. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11191. // Pointer lock
  11192. this._onPointerLockChange = function () {
  11193. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11194. document.webkitPointerLockElement === canvas ||
  11195. document.msPointerLockElement === canvas ||
  11196. document.pointerLockElement === canvas);
  11197. };
  11198. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11199. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11200. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11201. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11202. this._onVRDisplayPointerRestricted = function () {
  11203. if (canvas) {
  11204. canvas.requestPointerLock();
  11205. }
  11206. };
  11207. this._onVRDisplayPointerUnrestricted = function () {
  11208. document.exitPointerLock();
  11209. };
  11210. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11211. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11212. }
  11213. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11214. Engine.audioEngine = new BABYLON.AudioEngine();
  11215. }
  11216. // Prepare buffer pointers
  11217. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11218. this._currentBufferPointers[i] = new BufferPointer();
  11219. }
  11220. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11221. // Load WebVR Devices
  11222. if (options.autoEnableWebVR) {
  11223. this.initWebVR();
  11224. }
  11225. // Detect if we are running on a faulty buggy OS.
  11226. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11227. // Detect if we are running on a faulty buggy desktop OS.
  11228. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11229. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11230. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11231. }
  11232. Object.defineProperty(Engine, "LastCreatedEngine", {
  11233. /**
  11234. * Gets the latest created engine
  11235. */
  11236. get: function () {
  11237. if (Engine.Instances.length === 0) {
  11238. return null;
  11239. }
  11240. return Engine.Instances[Engine.Instances.length - 1];
  11241. },
  11242. enumerable: true,
  11243. configurable: true
  11244. });
  11245. Object.defineProperty(Engine, "LastCreatedScene", {
  11246. /**
  11247. * Gets the latest created scene
  11248. */
  11249. get: function () {
  11250. var lastCreatedEngine = Engine.LastCreatedEngine;
  11251. if (!lastCreatedEngine) {
  11252. return null;
  11253. }
  11254. if (lastCreatedEngine.scenes.length === 0) {
  11255. return null;
  11256. }
  11257. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11258. },
  11259. enumerable: true,
  11260. configurable: true
  11261. });
  11262. /**
  11263. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11264. * @param flag defines which part of the materials must be marked as dirty
  11265. * @param predicate defines a predicate used to filter which materials should be affected
  11266. */
  11267. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11268. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11269. var engine = Engine.Instances[engineIndex];
  11270. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11271. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11272. }
  11273. }
  11274. };
  11275. Object.defineProperty(Engine, "NEVER", {
  11276. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11277. get: function () {
  11278. return Engine._NEVER;
  11279. },
  11280. enumerable: true,
  11281. configurable: true
  11282. });
  11283. Object.defineProperty(Engine, "ALWAYS", {
  11284. /** 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 */
  11285. get: function () {
  11286. return Engine._ALWAYS;
  11287. },
  11288. enumerable: true,
  11289. configurable: true
  11290. });
  11291. Object.defineProperty(Engine, "LESS", {
  11292. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11293. get: function () {
  11294. return Engine._LESS;
  11295. },
  11296. enumerable: true,
  11297. configurable: true
  11298. });
  11299. Object.defineProperty(Engine, "EQUAL", {
  11300. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11301. get: function () {
  11302. return Engine._EQUAL;
  11303. },
  11304. enumerable: true,
  11305. configurable: true
  11306. });
  11307. Object.defineProperty(Engine, "LEQUAL", {
  11308. /** 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 */
  11309. get: function () {
  11310. return Engine._LEQUAL;
  11311. },
  11312. enumerable: true,
  11313. configurable: true
  11314. });
  11315. Object.defineProperty(Engine, "GREATER", {
  11316. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11317. get: function () {
  11318. return Engine._GREATER;
  11319. },
  11320. enumerable: true,
  11321. configurable: true
  11322. });
  11323. Object.defineProperty(Engine, "GEQUAL", {
  11324. /** 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 */
  11325. get: function () {
  11326. return Engine._GEQUAL;
  11327. },
  11328. enumerable: true,
  11329. configurable: true
  11330. });
  11331. Object.defineProperty(Engine, "NOTEQUAL", {
  11332. /** 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 */
  11333. get: function () {
  11334. return Engine._NOTEQUAL;
  11335. },
  11336. enumerable: true,
  11337. configurable: true
  11338. });
  11339. Object.defineProperty(Engine, "KEEP", {
  11340. /** Passed to stencilOperation to specify that stencil value must be kept */
  11341. get: function () {
  11342. return Engine._KEEP;
  11343. },
  11344. enumerable: true,
  11345. configurable: true
  11346. });
  11347. Object.defineProperty(Engine, "REPLACE", {
  11348. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11349. get: function () {
  11350. return Engine._REPLACE;
  11351. },
  11352. enumerable: true,
  11353. configurable: true
  11354. });
  11355. Object.defineProperty(Engine, "INCR", {
  11356. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11357. get: function () {
  11358. return Engine._INCR;
  11359. },
  11360. enumerable: true,
  11361. configurable: true
  11362. });
  11363. Object.defineProperty(Engine, "DECR", {
  11364. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11365. get: function () {
  11366. return Engine._DECR;
  11367. },
  11368. enumerable: true,
  11369. configurable: true
  11370. });
  11371. Object.defineProperty(Engine, "INVERT", {
  11372. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11373. get: function () {
  11374. return Engine._INVERT;
  11375. },
  11376. enumerable: true,
  11377. configurable: true
  11378. });
  11379. Object.defineProperty(Engine, "INCR_WRAP", {
  11380. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11381. get: function () {
  11382. return Engine._INCR_WRAP;
  11383. },
  11384. enumerable: true,
  11385. configurable: true
  11386. });
  11387. Object.defineProperty(Engine, "DECR_WRAP", {
  11388. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11389. get: function () {
  11390. return Engine._DECR_WRAP;
  11391. },
  11392. enumerable: true,
  11393. configurable: true
  11394. });
  11395. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11396. // Alpha
  11397. /** Defines that alpha blending is disabled */
  11398. get: function () {
  11399. return Engine._ALPHA_DISABLE;
  11400. },
  11401. enumerable: true,
  11402. configurable: true
  11403. });
  11404. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11405. /** Defines that alpha blending to SRC + DEST */
  11406. get: function () {
  11407. return Engine._ALPHA_ONEONE;
  11408. },
  11409. enumerable: true,
  11410. configurable: true
  11411. });
  11412. Object.defineProperty(Engine, "ALPHA_ADD", {
  11413. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11414. get: function () {
  11415. return Engine._ALPHA_ADD;
  11416. },
  11417. enumerable: true,
  11418. configurable: true
  11419. });
  11420. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11421. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11422. get: function () {
  11423. return Engine._ALPHA_COMBINE;
  11424. },
  11425. enumerable: true,
  11426. configurable: true
  11427. });
  11428. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11429. /** Defines that alpha blending to DEST - SRC * DEST */
  11430. get: function () {
  11431. return Engine._ALPHA_SUBTRACT;
  11432. },
  11433. enumerable: true,
  11434. configurable: true
  11435. });
  11436. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11437. /** Defines that alpha blending to SRC * DEST */
  11438. get: function () {
  11439. return Engine._ALPHA_MULTIPLY;
  11440. },
  11441. enumerable: true,
  11442. configurable: true
  11443. });
  11444. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11445. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11446. get: function () {
  11447. return Engine._ALPHA_MAXIMIZED;
  11448. },
  11449. enumerable: true,
  11450. configurable: true
  11451. });
  11452. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11453. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11454. get: function () {
  11455. return Engine._ALPHA_PREMULTIPLIED;
  11456. },
  11457. enumerable: true,
  11458. configurable: true
  11459. });
  11460. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11461. /**
  11462. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11463. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11464. */
  11465. get: function () {
  11466. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11467. },
  11468. enumerable: true,
  11469. configurable: true
  11470. });
  11471. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11472. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11473. get: function () {
  11474. return Engine._ALPHA_INTERPOLATE;
  11475. },
  11476. enumerable: true,
  11477. configurable: true
  11478. });
  11479. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11480. /**
  11481. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11482. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11483. */
  11484. get: function () {
  11485. return Engine._ALPHA_SCREENMODE;
  11486. },
  11487. enumerable: true,
  11488. configurable: true
  11489. });
  11490. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11491. // Delays
  11492. /** Defines that the ressource is not delayed*/
  11493. get: function () {
  11494. return Engine._DELAYLOADSTATE_NONE;
  11495. },
  11496. enumerable: true,
  11497. configurable: true
  11498. });
  11499. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11500. /** Defines that the ressource was successfully delay loaded */
  11501. get: function () {
  11502. return Engine._DELAYLOADSTATE_LOADED;
  11503. },
  11504. enumerable: true,
  11505. configurable: true
  11506. });
  11507. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11508. /** Defines that the ressource is currently delay loading */
  11509. get: function () {
  11510. return Engine._DELAYLOADSTATE_LOADING;
  11511. },
  11512. enumerable: true,
  11513. configurable: true
  11514. });
  11515. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11516. /** Defines that the ressource is delayed and has not started loading */
  11517. get: function () {
  11518. return Engine._DELAYLOADSTATE_NOTLOADED;
  11519. },
  11520. enumerable: true,
  11521. configurable: true
  11522. });
  11523. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11524. /** ALPHA */
  11525. get: function () {
  11526. return Engine._TEXTUREFORMAT_ALPHA;
  11527. },
  11528. enumerable: true,
  11529. configurable: true
  11530. });
  11531. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11532. /** LUMINANCE */
  11533. get: function () {
  11534. return Engine._TEXTUREFORMAT_LUMINANCE;
  11535. },
  11536. enumerable: true,
  11537. configurable: true
  11538. });
  11539. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11540. /**
  11541. * R32F
  11542. */
  11543. get: function () {
  11544. return Engine._TEXTUREFORMAT_R32F;
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11550. /**
  11551. * RG32F
  11552. */
  11553. get: function () {
  11554. return Engine._TEXTUREFORMAT_RG32F;
  11555. },
  11556. enumerable: true,
  11557. configurable: true
  11558. });
  11559. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11560. /**
  11561. * RGB32F
  11562. */
  11563. get: function () {
  11564. return Engine._TEXTUREFORMAT_RGB32F;
  11565. },
  11566. enumerable: true,
  11567. configurable: true
  11568. });
  11569. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11570. /**
  11571. * RGBA32F
  11572. */
  11573. get: function () {
  11574. return Engine._TEXTUREFORMAT_RGBA32F;
  11575. },
  11576. enumerable: true,
  11577. configurable: true
  11578. });
  11579. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11580. /** LUMINANCE_ALPHA */
  11581. get: function () {
  11582. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11583. },
  11584. enumerable: true,
  11585. configurable: true
  11586. });
  11587. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11588. /** RGB */
  11589. get: function () {
  11590. return Engine._TEXTUREFORMAT_RGB;
  11591. },
  11592. enumerable: true,
  11593. configurable: true
  11594. });
  11595. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11596. /** RGBA */
  11597. get: function () {
  11598. return Engine._TEXTUREFORMAT_RGBA;
  11599. },
  11600. enumerable: true,
  11601. configurable: true
  11602. });
  11603. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11604. /** UNSIGNED_INT */
  11605. get: function () {
  11606. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11607. },
  11608. enumerable: true,
  11609. configurable: true
  11610. });
  11611. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11612. /** FLOAT */
  11613. get: function () {
  11614. return Engine._TEXTURETYPE_FLOAT;
  11615. },
  11616. enumerable: true,
  11617. configurable: true
  11618. });
  11619. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11620. /** HALF_FLOAT */
  11621. get: function () {
  11622. return Engine._TEXTURETYPE_HALF_FLOAT;
  11623. },
  11624. enumerable: true,
  11625. configurable: true
  11626. });
  11627. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11628. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11629. get: function () {
  11630. return Engine._SCALEMODE_FLOOR;
  11631. },
  11632. enumerable: true,
  11633. configurable: true
  11634. });
  11635. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11636. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11637. get: function () {
  11638. return Engine._SCALEMODE_NEAREST;
  11639. },
  11640. enumerable: true,
  11641. configurable: true
  11642. });
  11643. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11644. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11645. get: function () {
  11646. return Engine._SCALEMODE_CEILING;
  11647. },
  11648. enumerable: true,
  11649. configurable: true
  11650. });
  11651. Object.defineProperty(Engine, "Version", {
  11652. /**
  11653. * Returns the current version of the framework
  11654. */
  11655. get: function () {
  11656. return "3.2.0-beta.4";
  11657. },
  11658. enumerable: true,
  11659. configurable: true
  11660. });
  11661. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11662. /**
  11663. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11664. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11665. */
  11666. get: function () {
  11667. return this._vrExclusivePointerMode;
  11668. },
  11669. enumerable: true,
  11670. configurable: true
  11671. });
  11672. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11673. /**
  11674. * Gets a boolean indicating that the engine supports uniform buffers
  11675. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11676. */
  11677. get: function () {
  11678. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11679. },
  11680. enumerable: true,
  11681. configurable: true
  11682. });
  11683. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11684. /**
  11685. * Gets a boolean indicating that only power of 2 textures are supported
  11686. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11687. */
  11688. get: function () {
  11689. return this._webGLVersion < 2 || this.forcePOTTextures;
  11690. },
  11691. enumerable: true,
  11692. configurable: true
  11693. });
  11694. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11695. /**
  11696. * Gets the performance monitor attached to this engine
  11697. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11698. */
  11699. get: function () {
  11700. return this._performanceMonitor;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11706. /**
  11707. * Gets the list of texture formats supported
  11708. */
  11709. get: function () {
  11710. return this._texturesSupported;
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11716. /**
  11717. * Gets the list of texture formats in use
  11718. */
  11719. get: function () {
  11720. return this._textureFormatInUse;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Engine.prototype, "currentViewport", {
  11726. /**
  11727. * Gets the current viewport
  11728. */
  11729. get: function () {
  11730. return this._cachedViewport;
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11736. /**
  11737. * Gets the default empty texture
  11738. */
  11739. get: function () {
  11740. if (!this._emptyTexture) {
  11741. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11742. }
  11743. return this._emptyTexture;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11749. /**
  11750. * Gets the default empty 3D texture
  11751. */
  11752. get: function () {
  11753. if (!this._emptyTexture3D) {
  11754. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11755. }
  11756. return this._emptyTexture3D;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11762. /**
  11763. * Gets the default empty cube texture
  11764. */
  11765. get: function () {
  11766. if (!this._emptyCubeTexture) {
  11767. var faceData = new Uint8Array(4);
  11768. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11769. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11770. }
  11771. return this._emptyCubeTexture;
  11772. },
  11773. enumerable: true,
  11774. configurable: true
  11775. });
  11776. Engine.prototype._rebuildInternalTextures = function () {
  11777. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11778. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11779. var internalTexture = currentState_1[_i];
  11780. internalTexture._rebuild();
  11781. }
  11782. };
  11783. Engine.prototype._rebuildEffects = function () {
  11784. for (var key in this._compiledEffects) {
  11785. var effect = this._compiledEffects[key];
  11786. effect._prepareEffect();
  11787. }
  11788. BABYLON.Effect.ResetCache();
  11789. };
  11790. Engine.prototype._rebuildBuffers = function () {
  11791. // Index / Vertex
  11792. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11793. var scene = _a[_i];
  11794. scene.resetCachedMaterial();
  11795. scene._rebuildGeometries();
  11796. scene._rebuildTextures();
  11797. }
  11798. // Uniforms
  11799. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11800. var uniformBuffer = _c[_b];
  11801. uniformBuffer._rebuild();
  11802. }
  11803. };
  11804. Engine.prototype._initGLContext = function () {
  11805. // Caps
  11806. this._caps = new EngineCapabilities();
  11807. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11808. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11809. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11810. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11811. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11812. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11813. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11814. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11815. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11816. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11817. // Infos
  11818. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11819. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11820. if (rendererInfo != null) {
  11821. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11822. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11823. }
  11824. if (!this._glVendor) {
  11825. this._glVendor = "Unknown vendor";
  11826. }
  11827. if (!this._glRenderer) {
  11828. this._glRenderer = "Unknown renderer";
  11829. }
  11830. // Constants
  11831. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11832. if (this._gl.RGBA16F !== 0x881A) {
  11833. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11834. }
  11835. if (this._gl.RGBA32F !== 0x8814) {
  11836. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11837. }
  11838. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11839. this._gl.DEPTH24_STENCIL8 = 35056;
  11840. }
  11841. // Extensions
  11842. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11843. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11844. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11845. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11846. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11847. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11848. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11849. 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');
  11850. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11851. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11852. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11853. this._caps.highPrecisionShaderSupported = true;
  11854. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11855. if (this._caps.timerQuery) {
  11856. if (this._webGLVersion === 1) {
  11857. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11858. }
  11859. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11860. }
  11861. // Checks if some of the format renders first to allow the use of webgl inspector.
  11862. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11863. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11864. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11865. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11866. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11867. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11868. if (this._webGLVersion > 1) {
  11869. this._gl.HALF_FLOAT_OES = 0x140B;
  11870. }
  11871. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11872. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11873. // Draw buffers
  11874. if (this._webGLVersion > 1) {
  11875. this._caps.drawBuffersExtension = true;
  11876. }
  11877. else {
  11878. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11879. if (drawBuffersExtension !== null) {
  11880. this._caps.drawBuffersExtension = true;
  11881. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11882. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11883. for (var i = 0; i < 16; i++) {
  11884. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11885. }
  11886. }
  11887. else {
  11888. this._caps.drawBuffersExtension = false;
  11889. }
  11890. }
  11891. // Depth Texture
  11892. if (this._webGLVersion > 1) {
  11893. this._caps.depthTextureExtension = true;
  11894. }
  11895. else {
  11896. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11897. if (depthTextureExtension != null) {
  11898. this._caps.depthTextureExtension = true;
  11899. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11900. }
  11901. }
  11902. // Vertex array object
  11903. if (this._webGLVersion > 1) {
  11904. this._caps.vertexArrayObject = true;
  11905. }
  11906. else {
  11907. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11908. if (vertexArrayObjectExtension != null) {
  11909. this._caps.vertexArrayObject = true;
  11910. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11911. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11912. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11913. }
  11914. else {
  11915. this._caps.vertexArrayObject = false;
  11916. }
  11917. }
  11918. // Instances count
  11919. if (this._webGLVersion > 1) {
  11920. this._caps.instancedArrays = true;
  11921. }
  11922. else {
  11923. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11924. if (instanceExtension != null) {
  11925. this._caps.instancedArrays = true;
  11926. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11927. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11928. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11929. }
  11930. else {
  11931. this._caps.instancedArrays = false;
  11932. }
  11933. }
  11934. // Intelligently add supported compressed formats in order to check for.
  11935. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11936. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11937. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11938. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11939. if (this._caps.astc)
  11940. this.texturesSupported.push('-astc.ktx');
  11941. if (this._caps.s3tc)
  11942. this.texturesSupported.push('-dxt.ktx');
  11943. if (this._caps.pvrtc)
  11944. this.texturesSupported.push('-pvrtc.ktx');
  11945. if (this._caps.etc2)
  11946. this.texturesSupported.push('-etc2.ktx');
  11947. if (this._caps.etc1)
  11948. this.texturesSupported.push('-etc1.ktx');
  11949. if (this._gl.getShaderPrecisionFormat) {
  11950. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11951. if (highp) {
  11952. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11953. }
  11954. }
  11955. // Depth buffer
  11956. this.setDepthBuffer(true);
  11957. this.setDepthFunctionToLessOrEqual();
  11958. this.setDepthWrite(true);
  11959. // Texture maps
  11960. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11961. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11962. this._nextFreeTextureSlots.push(slot);
  11963. }
  11964. };
  11965. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11966. /**
  11967. * Gets version of the current webGL context
  11968. */
  11969. get: function () {
  11970. return this._webGLVersion;
  11971. },
  11972. enumerable: true,
  11973. configurable: true
  11974. });
  11975. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11976. /**
  11977. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11978. */
  11979. get: function () {
  11980. return this._isStencilEnable;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Engine.prototype._prepareWorkingCanvas = function () {
  11986. if (this._workingCanvas) {
  11987. return;
  11988. }
  11989. this._workingCanvas = document.createElement("canvas");
  11990. var context = this._workingCanvas.getContext("2d");
  11991. if (context) {
  11992. this._workingContext = context;
  11993. }
  11994. };
  11995. /**
  11996. * Reset the texture cache to empty state
  11997. */
  11998. Engine.prototype.resetTextureCache = function () {
  11999. for (var key in this._boundTexturesCache) {
  12000. var boundTexture = this._boundTexturesCache[key];
  12001. if (boundTexture) {
  12002. this._removeDesignatedSlot(boundTexture);
  12003. }
  12004. this._boundTexturesCache[key] = null;
  12005. }
  12006. if (!this.disableTextureBindingOptimization) {
  12007. this._nextFreeTextureSlots = [];
  12008. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12009. this._nextFreeTextureSlots.push(slot);
  12010. }
  12011. }
  12012. this._currentTextureChannel = -1;
  12013. };
  12014. /**
  12015. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12016. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12017. * @returns true if engine is in deterministic lock step mode
  12018. */
  12019. Engine.prototype.isDeterministicLockStep = function () {
  12020. return this._deterministicLockstep;
  12021. };
  12022. /**
  12023. * Gets the max steps when engine is running in deterministic lock step
  12024. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12025. * @returns the max steps
  12026. */
  12027. Engine.prototype.getLockstepMaxSteps = function () {
  12028. return this._lockstepMaxSteps;
  12029. };
  12030. /**
  12031. * Gets an object containing information about the current webGL context
  12032. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12033. */
  12034. Engine.prototype.getGlInfo = function () {
  12035. return {
  12036. vendor: this._glVendor,
  12037. renderer: this._glRenderer,
  12038. version: this._glVersion
  12039. };
  12040. };
  12041. /**
  12042. * Gets current aspect ratio
  12043. * @param camera defines the camera to use to get the aspect ratio
  12044. * @param useScreen defines if screen size must be used (or the current render target if any)
  12045. * @returns a number defining the aspect ratio
  12046. */
  12047. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12048. if (useScreen === void 0) { useScreen = false; }
  12049. var viewport = camera.viewport;
  12050. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12051. };
  12052. /**
  12053. * Gets the current render width
  12054. * @param useScreen defines if screen size must be used (or the current render target if any)
  12055. * @returns a number defining the current render width
  12056. */
  12057. Engine.prototype.getRenderWidth = function (useScreen) {
  12058. if (useScreen === void 0) { useScreen = false; }
  12059. if (!useScreen && this._currentRenderTarget) {
  12060. return this._currentRenderTarget.width;
  12061. }
  12062. return this._gl.drawingBufferWidth;
  12063. };
  12064. /**
  12065. * Gets the current render height
  12066. * @param useScreen defines if screen size must be used (or the current render target if any)
  12067. * @returns a number defining the current render height
  12068. */
  12069. Engine.prototype.getRenderHeight = function (useScreen) {
  12070. if (useScreen === void 0) { useScreen = false; }
  12071. if (!useScreen && this._currentRenderTarget) {
  12072. return this._currentRenderTarget.height;
  12073. }
  12074. return this._gl.drawingBufferHeight;
  12075. };
  12076. /**
  12077. * Gets the HTML canvas attached with the current webGL context
  12078. * @returns a HTML canvas
  12079. */
  12080. Engine.prototype.getRenderingCanvas = function () {
  12081. return this._renderingCanvas;
  12082. };
  12083. /**
  12084. * Gets the client rect of the HTML canvas attached with the current webGL context
  12085. * @returns a client rectanglee
  12086. */
  12087. Engine.prototype.getRenderingCanvasClientRect = function () {
  12088. if (!this._renderingCanvas) {
  12089. return null;
  12090. }
  12091. return this._renderingCanvas.getBoundingClientRect();
  12092. };
  12093. /**
  12094. * Defines the hardware scaling level.
  12095. * By default the hardware scaling level is computed from the window device ratio.
  12096. * 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.
  12097. * @param level defines the level to use
  12098. */
  12099. Engine.prototype.setHardwareScalingLevel = function (level) {
  12100. this._hardwareScalingLevel = level;
  12101. this.resize();
  12102. };
  12103. /**
  12104. * Gets the current hardware scaling level.
  12105. * By default the hardware scaling level is computed from the window device ratio.
  12106. * 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.
  12107. * @returns a number indicating the current hardware scaling level
  12108. */
  12109. Engine.prototype.getHardwareScalingLevel = function () {
  12110. return this._hardwareScalingLevel;
  12111. };
  12112. /**
  12113. * Gets the list of loaded textures
  12114. * @returns an array containing all loaded textures
  12115. */
  12116. Engine.prototype.getLoadedTexturesCache = function () {
  12117. return this._internalTexturesCache;
  12118. };
  12119. /**
  12120. * Gets the object containing all engine capabilities
  12121. * @returns the EngineCapabilities object
  12122. */
  12123. Engine.prototype.getCaps = function () {
  12124. return this._caps;
  12125. };
  12126. Object.defineProperty(Engine.prototype, "drawCalls", {
  12127. /** @ignore */
  12128. get: function () {
  12129. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12130. return 0;
  12131. },
  12132. enumerable: true,
  12133. configurable: true
  12134. });
  12135. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12136. /** @ignore */
  12137. get: function () {
  12138. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12139. return null;
  12140. },
  12141. enumerable: true,
  12142. configurable: true
  12143. });
  12144. /**
  12145. * Gets the current depth function
  12146. * @returns a number defining the depth function
  12147. */
  12148. Engine.prototype.getDepthFunction = function () {
  12149. return this._depthCullingState.depthFunc;
  12150. };
  12151. /**
  12152. * Sets the current depth function
  12153. * @param depthFunc defines the function to use
  12154. */
  12155. Engine.prototype.setDepthFunction = function (depthFunc) {
  12156. this._depthCullingState.depthFunc = depthFunc;
  12157. };
  12158. /**
  12159. * Sets the current depth function to GREATER
  12160. */
  12161. Engine.prototype.setDepthFunctionToGreater = function () {
  12162. this._depthCullingState.depthFunc = this._gl.GREATER;
  12163. };
  12164. /**
  12165. * Sets the current depth function to GEQUAL
  12166. */
  12167. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12168. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12169. };
  12170. /**
  12171. * Sets the current depth function to LESS
  12172. */
  12173. Engine.prototype.setDepthFunctionToLess = function () {
  12174. this._depthCullingState.depthFunc = this._gl.LESS;
  12175. };
  12176. /**
  12177. * Sets the current depth function to LEQUAL
  12178. */
  12179. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12180. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12181. };
  12182. /**
  12183. * Gets a boolean indicating if stencil buffer is enabled
  12184. * @returns the current stencil buffer state
  12185. */
  12186. Engine.prototype.getStencilBuffer = function () {
  12187. return this._stencilState.stencilTest;
  12188. };
  12189. /**
  12190. * Enable or disable the stencil buffer
  12191. * @param enable defines if the stencil buffer must be enabled or disabled
  12192. */
  12193. Engine.prototype.setStencilBuffer = function (enable) {
  12194. this._stencilState.stencilTest = enable;
  12195. };
  12196. /**
  12197. * Gets the current stencil mask
  12198. * @returns a number defining the new stencil mask to use
  12199. */
  12200. Engine.prototype.getStencilMask = function () {
  12201. return this._stencilState.stencilMask;
  12202. };
  12203. /**
  12204. * Sets the current stencil mask
  12205. * @param mask defines the new stencil mask to use
  12206. */
  12207. Engine.prototype.setStencilMask = function (mask) {
  12208. this._stencilState.stencilMask = mask;
  12209. };
  12210. /**
  12211. * Gets the current stencil function
  12212. * @returns a number defining the stencil function to use
  12213. */
  12214. Engine.prototype.getStencilFunction = function () {
  12215. return this._stencilState.stencilFunc;
  12216. };
  12217. /**
  12218. * Gets the current stencil reference value
  12219. * @returns a number defining the stencil reference value to use
  12220. */
  12221. Engine.prototype.getStencilFunctionReference = function () {
  12222. return this._stencilState.stencilFuncRef;
  12223. };
  12224. /**
  12225. * Gets the current stencil mask
  12226. * @returns a number defining the stencil mask to use
  12227. */
  12228. Engine.prototype.getStencilFunctionMask = function () {
  12229. return this._stencilState.stencilFuncMask;
  12230. };
  12231. /**
  12232. * Sets the current stencil function
  12233. * @param stencilFunc defines the new stencil function to use
  12234. */
  12235. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12236. this._stencilState.stencilFunc = stencilFunc;
  12237. };
  12238. /**
  12239. * Sets the current stencil reference
  12240. * @param reference defines the new stencil reference to use
  12241. */
  12242. Engine.prototype.setStencilFunctionReference = function (reference) {
  12243. this._stencilState.stencilFuncRef = reference;
  12244. };
  12245. /**
  12246. * Sets the current stencil mask
  12247. * @param mask defines the new stencil mask to use
  12248. */
  12249. Engine.prototype.setStencilFunctionMask = function (mask) {
  12250. this._stencilState.stencilFuncMask = mask;
  12251. };
  12252. /**
  12253. * Gets the current stencil operation when stencil fails
  12254. * @returns a number defining stencil operation to use when stencil fails
  12255. */
  12256. Engine.prototype.getStencilOperationFail = function () {
  12257. return this._stencilState.stencilOpStencilFail;
  12258. };
  12259. /**
  12260. * Gets the current stencil operation when depth fails
  12261. * @returns a number defining stencil operation to use when depth fails
  12262. */
  12263. Engine.prototype.getStencilOperationDepthFail = function () {
  12264. return this._stencilState.stencilOpDepthFail;
  12265. };
  12266. /**
  12267. * Gets the current stencil operation when stencil passes
  12268. * @returns a number defining stencil operation to use when stencil passes
  12269. */
  12270. Engine.prototype.getStencilOperationPass = function () {
  12271. return this._stencilState.stencilOpStencilDepthPass;
  12272. };
  12273. /**
  12274. * Sets the stencil operation to use when stencil fails
  12275. * @param operation defines the stencil operation to use when stencil fails
  12276. */
  12277. Engine.prototype.setStencilOperationFail = function (operation) {
  12278. this._stencilState.stencilOpStencilFail = operation;
  12279. };
  12280. /**
  12281. * Sets the stencil operation to use when depth fails
  12282. * @param operation defines the stencil operation to use when depth fails
  12283. */
  12284. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12285. this._stencilState.stencilOpDepthFail = operation;
  12286. };
  12287. /**
  12288. * Sets the stencil operation to use when stencil passes
  12289. * @param operation defines the stencil operation to use when stencil passes
  12290. */
  12291. Engine.prototype.setStencilOperationPass = function (operation) {
  12292. this._stencilState.stencilOpStencilDepthPass = operation;
  12293. };
  12294. /**
  12295. * Sets a boolean indicating if the dithering state is enabled or disabled
  12296. * @param value defines the dithering state
  12297. */
  12298. Engine.prototype.setDitheringState = function (value) {
  12299. if (value) {
  12300. this._gl.enable(this._gl.DITHER);
  12301. }
  12302. else {
  12303. this._gl.disable(this._gl.DITHER);
  12304. }
  12305. };
  12306. /**
  12307. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12308. * @param value defines the rasterizer state
  12309. */
  12310. Engine.prototype.setRasterizerState = function (value) {
  12311. if (value) {
  12312. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12313. }
  12314. else {
  12315. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12316. }
  12317. };
  12318. /**
  12319. * stop executing a render loop function and remove it from the execution array
  12320. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12321. */
  12322. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12323. if (!renderFunction) {
  12324. this._activeRenderLoops = [];
  12325. return;
  12326. }
  12327. var index = this._activeRenderLoops.indexOf(renderFunction);
  12328. if (index >= 0) {
  12329. this._activeRenderLoops.splice(index, 1);
  12330. }
  12331. };
  12332. /** @ignore */
  12333. Engine.prototype._renderLoop = function () {
  12334. if (!this._contextWasLost) {
  12335. var shouldRender = true;
  12336. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12337. shouldRender = false;
  12338. }
  12339. if (shouldRender) {
  12340. // Start new frame
  12341. this.beginFrame();
  12342. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12343. var renderFunction = this._activeRenderLoops[index];
  12344. renderFunction();
  12345. }
  12346. // Present
  12347. this.endFrame();
  12348. }
  12349. }
  12350. if (this._activeRenderLoops.length > 0) {
  12351. // Register new frame
  12352. var requester = null;
  12353. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12354. requester = this._vrDisplay;
  12355. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12356. }
  12357. else {
  12358. this._renderingQueueLaunched = false;
  12359. }
  12360. };
  12361. /**
  12362. * Register and execute a render loop. The engine can have more than one render function
  12363. * @param renderFunction defines the function to continuously execute
  12364. */
  12365. Engine.prototype.runRenderLoop = function (renderFunction) {
  12366. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12367. return;
  12368. }
  12369. this._activeRenderLoops.push(renderFunction);
  12370. if (!this._renderingQueueLaunched) {
  12371. this._renderingQueueLaunched = true;
  12372. this._bindedRenderFunction = this._renderLoop.bind(this);
  12373. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12374. }
  12375. };
  12376. /**
  12377. * Toggle full screen mode
  12378. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12379. * @param options defines an option object to be sent to the requestFullscreen function
  12380. */
  12381. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12382. if (this.isFullscreen) {
  12383. BABYLON.Tools.ExitFullscreen();
  12384. }
  12385. else {
  12386. this._pointerLockRequested = requestPointerLock;
  12387. if (this._renderingCanvas) {
  12388. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12389. }
  12390. }
  12391. };
  12392. /**
  12393. * Clear the current render buffer or the current render target (if any is set up)
  12394. * @param color defines the color to use
  12395. * @param backBuffer defines if the back buffer must be cleared
  12396. * @param depth defines if the depth buffer must be cleared
  12397. * @param stencil defines if the stencil buffer must be cleared
  12398. */
  12399. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12400. if (stencil === void 0) { stencil = false; }
  12401. this.applyStates();
  12402. var mode = 0;
  12403. if (backBuffer && color) {
  12404. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12405. mode |= this._gl.COLOR_BUFFER_BIT;
  12406. }
  12407. if (depth) {
  12408. this._gl.clearDepth(1.0);
  12409. mode |= this._gl.DEPTH_BUFFER_BIT;
  12410. }
  12411. if (stencil) {
  12412. this._gl.clearStencil(0);
  12413. mode |= this._gl.STENCIL_BUFFER_BIT;
  12414. }
  12415. this._gl.clear(mode);
  12416. };
  12417. /**
  12418. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12419. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12420. * @param y defines the y-coordinate of the corner of the clear rectangle
  12421. * @param width defines the width of the clear rectangle
  12422. * @param height defines the height of the clear rectangle
  12423. * @param clearColor defines the clear color
  12424. */
  12425. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12426. var gl = this._gl;
  12427. // Save state
  12428. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12429. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12430. // Change state
  12431. gl.enable(gl.SCISSOR_TEST);
  12432. gl.scissor(x, y, width, height);
  12433. // Clear
  12434. this.clear(clearColor, true, true, true);
  12435. // Restore state
  12436. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12437. if (curScissor === true) {
  12438. gl.enable(gl.SCISSOR_TEST);
  12439. }
  12440. else {
  12441. gl.disable(gl.SCISSOR_TEST);
  12442. }
  12443. };
  12444. /**
  12445. * Set the WebGL's viewport
  12446. * @param viewport defines the viewport element to be used
  12447. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12448. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12449. */
  12450. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12451. var width = requiredWidth || this.getRenderWidth();
  12452. var height = requiredHeight || this.getRenderHeight();
  12453. var x = viewport.x || 0;
  12454. var y = viewport.y || 0;
  12455. this._cachedViewport = viewport;
  12456. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12457. };
  12458. /**
  12459. * Directly set the WebGL Viewport
  12460. * @param x defines the x coordinate of the viewport (in screen space)
  12461. * @param y defines the y coordinate of the viewport (in screen space)
  12462. * @param width defines the width of the viewport (in screen space)
  12463. * @param height defines the height of the viewport (in screen space)
  12464. * @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
  12465. */
  12466. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12467. var currentViewport = this._cachedViewport;
  12468. this._cachedViewport = null;
  12469. this._gl.viewport(x, y, width, height);
  12470. return currentViewport;
  12471. };
  12472. /**
  12473. * Begin a new frame
  12474. */
  12475. Engine.prototype.beginFrame = function () {
  12476. this.onBeginFrameObservable.notifyObservers(this);
  12477. this._measureFps();
  12478. };
  12479. /**
  12480. * Enf the current frame
  12481. */
  12482. Engine.prototype.endFrame = function () {
  12483. // Force a flush in case we are using a bad OS.
  12484. if (this._badOS) {
  12485. this.flushFramebuffer();
  12486. }
  12487. // Submit frame to the vr device, if enabled
  12488. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12489. // TODO: We should only submit the frame if we read frameData successfully.
  12490. this._vrDisplay.submitFrame();
  12491. }
  12492. this.onEndFrameObservable.notifyObservers(this);
  12493. };
  12494. /**
  12495. * Resize the view according to the canvas' size
  12496. */
  12497. Engine.prototype.resize = function () {
  12498. // We're not resizing the size of the canvas while in VR mode & presenting
  12499. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12500. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12501. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12502. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12503. }
  12504. };
  12505. /**
  12506. * Force a specific size of the canvas
  12507. * @param width defines the new canvas' width
  12508. * @param height defines the new canvas' height
  12509. */
  12510. Engine.prototype.setSize = function (width, height) {
  12511. if (!this._renderingCanvas) {
  12512. return;
  12513. }
  12514. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12515. return;
  12516. }
  12517. this._renderingCanvas.width = width;
  12518. this._renderingCanvas.height = height;
  12519. for (var index = 0; index < this.scenes.length; index++) {
  12520. var scene = this.scenes[index];
  12521. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12522. var cam = scene.cameras[camIndex];
  12523. cam._currentRenderId = 0;
  12524. }
  12525. }
  12526. if (this.onResizeObservable.hasObservers) {
  12527. this.onResizeObservable.notifyObservers(this);
  12528. }
  12529. };
  12530. // WebVR functions
  12531. /**
  12532. * Gets a boolean indicating if a webVR device was detected
  12533. * @returns true if a webVR device was detected
  12534. */
  12535. Engine.prototype.isVRDevicePresent = function () {
  12536. return !!this._vrDisplay;
  12537. };
  12538. /**
  12539. * Gets the current webVR device
  12540. * @returns the current webVR device (or null)
  12541. */
  12542. Engine.prototype.getVRDevice = function () {
  12543. return this._vrDisplay;
  12544. };
  12545. /**
  12546. * Initializes a webVR display and starts listening to display change events
  12547. * The onVRDisplayChangedObservable will be notified upon these changes
  12548. * @returns The onVRDisplayChangedObservable
  12549. */
  12550. Engine.prototype.initWebVR = function () {
  12551. this.initWebVRAsync();
  12552. return this.onVRDisplayChangedObservable;
  12553. };
  12554. /**
  12555. * Initializes a webVR display and starts listening to display change events
  12556. * The onVRDisplayChangedObservable will be notified upon these changes
  12557. * @returns A promise containing a VRDisplay and if vr is supported
  12558. */
  12559. Engine.prototype.initWebVRAsync = function () {
  12560. var _this = this;
  12561. var notifyObservers = function () {
  12562. var eventArgs = {
  12563. vrDisplay: _this._vrDisplay,
  12564. vrSupported: _this._vrSupported
  12565. };
  12566. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12567. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12568. };
  12569. if (!this._onVrDisplayConnect) {
  12570. this._onVrDisplayConnect = function (event) {
  12571. _this._vrDisplay = event.display;
  12572. notifyObservers();
  12573. };
  12574. this._onVrDisplayDisconnect = function () {
  12575. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12576. _this._vrDisplay = undefined;
  12577. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12578. notifyObservers();
  12579. };
  12580. this._onVrDisplayPresentChange = function () {
  12581. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12582. };
  12583. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12584. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12585. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12586. }
  12587. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12588. this._webVRInitPromise.then(notifyObservers);
  12589. return this._webVRInitPromise;
  12590. };
  12591. /**
  12592. * Call this function to switch to webVR mode
  12593. * Will do nothing if webVR is not supported or if there is no webVR device
  12594. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12595. */
  12596. Engine.prototype.enableVR = function () {
  12597. var _this = this;
  12598. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12599. var onResolved = function () {
  12600. _this.onVRRequestPresentComplete.notifyObservers(true);
  12601. _this._onVRFullScreenTriggered();
  12602. };
  12603. var onRejected = function () {
  12604. _this.onVRRequestPresentComplete.notifyObservers(false);
  12605. };
  12606. this.onVRRequestPresentStart.notifyObservers(this);
  12607. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12608. }
  12609. };
  12610. /**
  12611. * Call this function to leave webVR mode
  12612. * Will do nothing if webVR is not supported or if there is no webVR device
  12613. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12614. */
  12615. Engine.prototype.disableVR = function () {
  12616. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12617. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12618. }
  12619. };
  12620. Engine.prototype._getVRDisplaysAsync = function () {
  12621. var _this = this;
  12622. return new Promise(function (res, rej) {
  12623. if (navigator.getVRDisplays) {
  12624. navigator.getVRDisplays().then(function (devices) {
  12625. _this._vrSupported = true;
  12626. // note that devices may actually be an empty array. This is fine;
  12627. // we expect this._vrDisplay to be undefined in this case.
  12628. _this._vrDisplay = devices[0];
  12629. res({
  12630. vrDisplay: _this._vrDisplay,
  12631. vrSupported: _this._vrSupported
  12632. });
  12633. });
  12634. }
  12635. else {
  12636. _this._vrDisplay = undefined;
  12637. _this._vrSupported = false;
  12638. res({
  12639. vrDisplay: _this._vrDisplay,
  12640. vrSupported: _this._vrSupported
  12641. });
  12642. }
  12643. });
  12644. };
  12645. /**
  12646. * Binds the frame buffer to the specified texture.
  12647. * @param texture The texture to render to or null for the default canvas
  12648. * @param faceIndex The face of the texture to render to in case of cube texture
  12649. * @param requiredWidth The width of the target to render to
  12650. * @param requiredHeight The height of the target to render to
  12651. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12652. * @param depthStencilTexture The depth stencil texture to use to render
  12653. */
  12654. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12655. if (this._currentRenderTarget) {
  12656. this.unBindFramebuffer(this._currentRenderTarget);
  12657. }
  12658. this._currentRenderTarget = texture;
  12659. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12660. var gl = this._gl;
  12661. if (texture.isCube) {
  12662. if (faceIndex === undefined) {
  12663. faceIndex = 0;
  12664. }
  12665. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12666. if (depthStencilTexture) {
  12667. if (depthStencilTexture._generateStencilBuffer) {
  12668. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12669. }
  12670. else {
  12671. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12672. }
  12673. }
  12674. }
  12675. if (this._cachedViewport && !forceFullscreenViewport) {
  12676. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12677. }
  12678. else {
  12679. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12680. }
  12681. this.wipeCaches();
  12682. };
  12683. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12684. if (this._currentFramebuffer !== framebuffer) {
  12685. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12686. this._currentFramebuffer = framebuffer;
  12687. }
  12688. };
  12689. /**
  12690. * Unbind the current render target texture from the webGL context
  12691. * @param texture defines the render target texture to unbind
  12692. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12693. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12694. */
  12695. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12696. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12697. this._currentRenderTarget = null;
  12698. // If MSAA, we need to bitblt back to main texture
  12699. var gl = this._gl;
  12700. if (texture._MSAAFramebuffer) {
  12701. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12702. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12703. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12704. }
  12705. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12706. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12707. gl.generateMipmap(gl.TEXTURE_2D);
  12708. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12709. }
  12710. if (onBeforeUnbind) {
  12711. if (texture._MSAAFramebuffer) {
  12712. // Bind the correct framebuffer
  12713. this.bindUnboundFramebuffer(texture._framebuffer);
  12714. }
  12715. onBeforeUnbind();
  12716. }
  12717. this.bindUnboundFramebuffer(null);
  12718. };
  12719. /**
  12720. * Unbind a list of render target textures from the webGL context
  12721. * This is used only when drawBuffer extension or webGL2 are active
  12722. * @param textures defines the render target textures to unbind
  12723. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12724. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12725. */
  12726. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12727. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12728. this._currentRenderTarget = null;
  12729. // If MSAA, we need to bitblt back to main texture
  12730. var gl = this._gl;
  12731. if (textures[0]._MSAAFramebuffer) {
  12732. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12733. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12734. var attachments = textures[0]._attachments;
  12735. if (!attachments) {
  12736. attachments = new Array(textures.length);
  12737. textures[0]._attachments = attachments;
  12738. }
  12739. for (var i = 0; i < textures.length; i++) {
  12740. var texture = textures[i];
  12741. for (var j = 0; j < attachments.length; j++) {
  12742. attachments[j] = gl.NONE;
  12743. }
  12744. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12745. gl.readBuffer(attachments[i]);
  12746. gl.drawBuffers(attachments);
  12747. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12748. }
  12749. for (var i = 0; i < attachments.length; i++) {
  12750. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12751. }
  12752. gl.drawBuffers(attachments);
  12753. }
  12754. for (var i = 0; i < textures.length; i++) {
  12755. var texture = textures[i];
  12756. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12757. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12758. gl.generateMipmap(gl.TEXTURE_2D);
  12759. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12760. }
  12761. }
  12762. if (onBeforeUnbind) {
  12763. if (textures[0]._MSAAFramebuffer) {
  12764. // Bind the correct framebuffer
  12765. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12766. }
  12767. onBeforeUnbind();
  12768. }
  12769. this.bindUnboundFramebuffer(null);
  12770. };
  12771. /**
  12772. * Force the mipmap generation for the given render target texture
  12773. * @param texture defines the render target texture to use
  12774. */
  12775. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12776. if (texture.generateMipMaps) {
  12777. var gl = this._gl;
  12778. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12779. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12780. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12781. }
  12782. };
  12783. /**
  12784. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12785. */
  12786. Engine.prototype.flushFramebuffer = function () {
  12787. this._gl.flush();
  12788. };
  12789. /**
  12790. * Unbind the current render target and bind the default framebuffer
  12791. */
  12792. Engine.prototype.restoreDefaultFramebuffer = function () {
  12793. if (this._currentRenderTarget) {
  12794. this.unBindFramebuffer(this._currentRenderTarget);
  12795. }
  12796. else {
  12797. this.bindUnboundFramebuffer(null);
  12798. }
  12799. if (this._cachedViewport) {
  12800. this.setViewport(this._cachedViewport);
  12801. }
  12802. this.wipeCaches();
  12803. };
  12804. // UBOs
  12805. /**
  12806. * Create an uniform buffer
  12807. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12808. * @param elements defines the content of the uniform buffer
  12809. * @returns the webGL uniform buffer
  12810. */
  12811. Engine.prototype.createUniformBuffer = function (elements) {
  12812. var ubo = this._gl.createBuffer();
  12813. if (!ubo) {
  12814. throw new Error("Unable to create uniform buffer");
  12815. }
  12816. this.bindUniformBuffer(ubo);
  12817. if (elements instanceof Float32Array) {
  12818. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12819. }
  12820. else {
  12821. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12822. }
  12823. this.bindUniformBuffer(null);
  12824. ubo.references = 1;
  12825. return ubo;
  12826. };
  12827. /**
  12828. * Create a dynamic uniform buffer
  12829. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12830. * @param elements defines the content of the uniform buffer
  12831. * @returns the webGL uniform buffer
  12832. */
  12833. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12834. var ubo = this._gl.createBuffer();
  12835. if (!ubo) {
  12836. throw new Error("Unable to create dynamic uniform buffer");
  12837. }
  12838. this.bindUniformBuffer(ubo);
  12839. if (elements instanceof Float32Array) {
  12840. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12841. }
  12842. else {
  12843. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12844. }
  12845. this.bindUniformBuffer(null);
  12846. ubo.references = 1;
  12847. return ubo;
  12848. };
  12849. /**
  12850. * Update an existing uniform buffer
  12851. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12852. * @param uniformBuffer defines the target uniform buffer
  12853. * @param elements defines the content to update
  12854. * @param offset defines the offset in the uniform buffer where update should start
  12855. * @param count defines the size of the data to update
  12856. */
  12857. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12858. this.bindUniformBuffer(uniformBuffer);
  12859. if (offset === undefined) {
  12860. offset = 0;
  12861. }
  12862. if (count === undefined) {
  12863. if (elements instanceof Float32Array) {
  12864. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12865. }
  12866. else {
  12867. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12868. }
  12869. }
  12870. else {
  12871. if (elements instanceof Float32Array) {
  12872. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12873. }
  12874. else {
  12875. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12876. }
  12877. }
  12878. this.bindUniformBuffer(null);
  12879. };
  12880. // VBOs
  12881. Engine.prototype._resetVertexBufferBinding = function () {
  12882. this.bindArrayBuffer(null);
  12883. this._cachedVertexBuffers = null;
  12884. };
  12885. /**
  12886. * Creates a vertex buffer
  12887. * @param data the data for the vertex buffer
  12888. * @returns the new WebGL static buffer
  12889. */
  12890. Engine.prototype.createVertexBuffer = function (data) {
  12891. var vbo = this._gl.createBuffer();
  12892. if (!vbo) {
  12893. throw new Error("Unable to create vertex buffer");
  12894. }
  12895. this.bindArrayBuffer(vbo);
  12896. if (data instanceof Array) {
  12897. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12898. }
  12899. else {
  12900. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12901. }
  12902. this._resetVertexBufferBinding();
  12903. vbo.references = 1;
  12904. return vbo;
  12905. };
  12906. /**
  12907. * Creates a dynamic vertex buffer
  12908. * @param data the data for the dynamic vertex buffer
  12909. * @returns the new WebGL dynamic buffer
  12910. */
  12911. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12912. var vbo = this._gl.createBuffer();
  12913. if (!vbo) {
  12914. throw new Error("Unable to create dynamic vertex buffer");
  12915. }
  12916. this.bindArrayBuffer(vbo);
  12917. if (data instanceof Array) {
  12918. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12919. }
  12920. else {
  12921. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12922. }
  12923. this._resetVertexBufferBinding();
  12924. vbo.references = 1;
  12925. return vbo;
  12926. };
  12927. /**
  12928. * Update a dynamic index buffer
  12929. * @param indexBuffer defines the target index buffer
  12930. * @param indices defines the data to update
  12931. * @param offset defines the offset in the target index buffer where update should start
  12932. */
  12933. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12934. if (offset === void 0) { offset = 0; }
  12935. // Force cache update
  12936. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12937. this.bindIndexBuffer(indexBuffer);
  12938. var arrayBuffer;
  12939. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12940. arrayBuffer = indices;
  12941. }
  12942. else {
  12943. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12944. }
  12945. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12946. this._resetIndexBufferBinding();
  12947. };
  12948. /**
  12949. * Updates a dynamic vertex buffer.
  12950. * @param vertexBuffer the vertex buffer to update
  12951. * @param data the data used to update the vertex buffer
  12952. * @param byteOffset the byte offset of the data
  12953. * @param byteLength the byte length of the data
  12954. */
  12955. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  12956. this.bindArrayBuffer(vertexBuffer);
  12957. if (byteOffset === undefined) {
  12958. byteOffset = 0;
  12959. }
  12960. if (byteLength === undefined) {
  12961. if (data instanceof Array) {
  12962. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  12963. }
  12964. else {
  12965. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  12966. }
  12967. }
  12968. else {
  12969. if (data instanceof Array) {
  12970. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  12971. }
  12972. else {
  12973. if (data instanceof ArrayBuffer) {
  12974. data = new Uint8Array(data, byteOffset, byteLength);
  12975. }
  12976. else {
  12977. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  12978. }
  12979. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12980. }
  12981. }
  12982. this._resetVertexBufferBinding();
  12983. };
  12984. Engine.prototype._resetIndexBufferBinding = function () {
  12985. this.bindIndexBuffer(null);
  12986. this._cachedIndexBuffer = null;
  12987. };
  12988. /**
  12989. * Creates a new index buffer
  12990. * @param indices defines the content of the index buffer
  12991. * @param updatable defines if the index buffer must be updatable
  12992. * @returns a new webGL buffer
  12993. */
  12994. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12995. var vbo = this._gl.createBuffer();
  12996. if (!vbo) {
  12997. throw new Error("Unable to create index buffer");
  12998. }
  12999. this.bindIndexBuffer(vbo);
  13000. // Check for 32 bits indices
  13001. var arrayBuffer;
  13002. var need32Bits = false;
  13003. if (indices instanceof Uint16Array) {
  13004. arrayBuffer = indices;
  13005. }
  13006. else {
  13007. //check 32 bit support
  13008. if (this._caps.uintIndices) {
  13009. if (indices instanceof Uint32Array) {
  13010. arrayBuffer = indices;
  13011. need32Bits = true;
  13012. }
  13013. else {
  13014. //number[] or Int32Array, check if 32 bit is necessary
  13015. for (var index = 0; index < indices.length; index++) {
  13016. if (indices[index] > 65535) {
  13017. need32Bits = true;
  13018. break;
  13019. }
  13020. }
  13021. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13022. }
  13023. }
  13024. else {
  13025. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13026. arrayBuffer = new Uint16Array(indices);
  13027. }
  13028. }
  13029. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13030. this._resetIndexBufferBinding();
  13031. vbo.references = 1;
  13032. vbo.is32Bits = need32Bits;
  13033. return vbo;
  13034. };
  13035. /**
  13036. * Bind a webGL buffer to the webGL context
  13037. * @param buffer defines the buffer to bind
  13038. */
  13039. Engine.prototype.bindArrayBuffer = function (buffer) {
  13040. if (!this._vaoRecordInProgress) {
  13041. this._unbindVertexArrayObject();
  13042. }
  13043. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13044. };
  13045. /**
  13046. * Bind an uniform buffer to the current webGL context
  13047. * @param buffer defines the buffer to bind
  13048. */
  13049. Engine.prototype.bindUniformBuffer = function (buffer) {
  13050. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13051. };
  13052. /**
  13053. * Bind a buffer to the current webGL context at a given location
  13054. * @param buffer defines the buffer to bind
  13055. * @param location defines the index where to bind the buffer
  13056. */
  13057. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13058. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13059. };
  13060. /**
  13061. * Bind a specific block at a given index in a specific shader program
  13062. * @param shaderProgram defines the shader program
  13063. * @param blockName defines the block name
  13064. * @param index defines the index where to bind the block
  13065. */
  13066. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13067. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13068. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13069. };
  13070. ;
  13071. Engine.prototype.bindIndexBuffer = function (buffer) {
  13072. if (!this._vaoRecordInProgress) {
  13073. this._unbindVertexArrayObject();
  13074. }
  13075. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13076. };
  13077. Engine.prototype.bindBuffer = function (buffer, target) {
  13078. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13079. this._gl.bindBuffer(target, buffer);
  13080. this._currentBoundBuffer[target] = buffer;
  13081. }
  13082. };
  13083. /**
  13084. * update the bound buffer with the given data
  13085. * @param data defines the data to update
  13086. */
  13087. Engine.prototype.updateArrayBuffer = function (data) {
  13088. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13089. };
  13090. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13091. var pointer = this._currentBufferPointers[indx];
  13092. var changed = false;
  13093. if (!pointer.active) {
  13094. changed = true;
  13095. pointer.active = true;
  13096. pointer.index = indx;
  13097. pointer.size = size;
  13098. pointer.type = type;
  13099. pointer.normalized = normalized;
  13100. pointer.stride = stride;
  13101. pointer.offset = offset;
  13102. pointer.buffer = buffer;
  13103. }
  13104. else {
  13105. if (pointer.buffer !== buffer) {
  13106. pointer.buffer = buffer;
  13107. changed = true;
  13108. }
  13109. if (pointer.size !== size) {
  13110. pointer.size = size;
  13111. changed = true;
  13112. }
  13113. if (pointer.type !== type) {
  13114. pointer.type = type;
  13115. changed = true;
  13116. }
  13117. if (pointer.normalized !== normalized) {
  13118. pointer.normalized = normalized;
  13119. changed = true;
  13120. }
  13121. if (pointer.stride !== stride) {
  13122. pointer.stride = stride;
  13123. changed = true;
  13124. }
  13125. if (pointer.offset !== offset) {
  13126. pointer.offset = offset;
  13127. changed = true;
  13128. }
  13129. }
  13130. if (changed || this._vaoRecordInProgress) {
  13131. this.bindArrayBuffer(buffer);
  13132. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13133. }
  13134. };
  13135. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13136. if (indexBuffer == null) {
  13137. return;
  13138. }
  13139. if (this._cachedIndexBuffer !== indexBuffer) {
  13140. this._cachedIndexBuffer = indexBuffer;
  13141. this.bindIndexBuffer(indexBuffer);
  13142. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13143. }
  13144. };
  13145. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13146. var attributes = effect.getAttributesNames();
  13147. if (!this._vaoRecordInProgress) {
  13148. this._unbindVertexArrayObject();
  13149. }
  13150. this.unbindAllAttributes();
  13151. for (var index = 0; index < attributes.length; index++) {
  13152. var order = effect.getAttributeLocation(index);
  13153. if (order >= 0) {
  13154. var vertexBuffer = vertexBuffers[attributes[index]];
  13155. if (!vertexBuffer) {
  13156. continue;
  13157. }
  13158. this._gl.enableVertexAttribArray(order);
  13159. if (!this._vaoRecordInProgress) {
  13160. this._vertexAttribArraysEnabled[order] = true;
  13161. }
  13162. var buffer = vertexBuffer.getBuffer();
  13163. if (buffer) {
  13164. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13165. if (vertexBuffer.getIsInstanced()) {
  13166. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13167. if (!this._vaoRecordInProgress) {
  13168. this._currentInstanceLocations.push(order);
  13169. this._currentInstanceBuffers.push(buffer);
  13170. }
  13171. }
  13172. }
  13173. }
  13174. }
  13175. };
  13176. /**
  13177. * Records a vertex array object
  13178. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13179. * @param vertexBuffers defines the list of vertex buffers to store
  13180. * @param indexBuffer defines the index buffer to store
  13181. * @param effect defines the effect to store
  13182. * @returns the new vertex array object
  13183. */
  13184. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13185. var vao = this._gl.createVertexArray();
  13186. this._vaoRecordInProgress = true;
  13187. this._gl.bindVertexArray(vao);
  13188. this._mustWipeVertexAttributes = true;
  13189. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13190. this.bindIndexBuffer(indexBuffer);
  13191. this._vaoRecordInProgress = false;
  13192. this._gl.bindVertexArray(null);
  13193. return vao;
  13194. };
  13195. /**
  13196. * Bind a specific vertex array object
  13197. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13198. * @param vertexArrayObject defines the vertex array object to bind
  13199. * @param indexBuffer defines the index buffer to bind
  13200. */
  13201. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13202. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13203. this._cachedVertexArrayObject = vertexArrayObject;
  13204. this._gl.bindVertexArray(vertexArrayObject);
  13205. this._cachedVertexBuffers = null;
  13206. this._cachedIndexBuffer = null;
  13207. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13208. this._mustWipeVertexAttributes = true;
  13209. }
  13210. };
  13211. /**
  13212. * Bind webGl buffers directly to the webGL context
  13213. * @param vertexBuffer defines the vertex buffer to bind
  13214. * @param indexBuffer defines the index buffer to bind
  13215. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13216. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13217. * @param effect defines the effect associated with the vertex buffer
  13218. */
  13219. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13220. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13221. this._cachedVertexBuffers = vertexBuffer;
  13222. this._cachedEffectForVertexBuffers = effect;
  13223. var attributesCount = effect.getAttributesCount();
  13224. this._unbindVertexArrayObject();
  13225. this.unbindAllAttributes();
  13226. var offset = 0;
  13227. for (var index = 0; index < attributesCount; index++) {
  13228. if (index < vertexDeclaration.length) {
  13229. var order = effect.getAttributeLocation(index);
  13230. if (order >= 0) {
  13231. this._gl.enableVertexAttribArray(order);
  13232. this._vertexAttribArraysEnabled[order] = true;
  13233. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13234. }
  13235. offset += vertexDeclaration[index] * 4;
  13236. }
  13237. }
  13238. }
  13239. this._bindIndexBufferWithCache(indexBuffer);
  13240. };
  13241. Engine.prototype._unbindVertexArrayObject = function () {
  13242. if (!this._cachedVertexArrayObject) {
  13243. return;
  13244. }
  13245. this._cachedVertexArrayObject = null;
  13246. this._gl.bindVertexArray(null);
  13247. };
  13248. /**
  13249. * Bind a list of vertex buffers to the webGL context
  13250. * @param vertexBuffers defines the list of vertex buffers to bind
  13251. * @param indexBuffer defines the index buffer to bind
  13252. * @param effect defines the effect associated with the vertex buffers
  13253. */
  13254. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13255. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13256. this._cachedVertexBuffers = vertexBuffers;
  13257. this._cachedEffectForVertexBuffers = effect;
  13258. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13259. }
  13260. this._bindIndexBufferWithCache(indexBuffer);
  13261. };
  13262. /**
  13263. * Unbind all instance attributes
  13264. */
  13265. Engine.prototype.unbindInstanceAttributes = function () {
  13266. var boundBuffer;
  13267. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13268. var instancesBuffer = this._currentInstanceBuffers[i];
  13269. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13270. boundBuffer = instancesBuffer;
  13271. this.bindArrayBuffer(instancesBuffer);
  13272. }
  13273. var offsetLocation = this._currentInstanceLocations[i];
  13274. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13275. }
  13276. this._currentInstanceBuffers.length = 0;
  13277. this._currentInstanceLocations.length = 0;
  13278. };
  13279. /**
  13280. * Release and free the memory of a vertex array object
  13281. * @param vao defines the vertex array object to delete
  13282. */
  13283. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13284. this._gl.deleteVertexArray(vao);
  13285. };
  13286. /** @ignore */
  13287. Engine.prototype._releaseBuffer = function (buffer) {
  13288. buffer.references--;
  13289. if (buffer.references === 0) {
  13290. this._gl.deleteBuffer(buffer);
  13291. return true;
  13292. }
  13293. return false;
  13294. };
  13295. /**
  13296. * Creates a webGL buffer to use with instanciation
  13297. * @param capacity defines the size of the buffer
  13298. * @returns the webGL buffer
  13299. */
  13300. Engine.prototype.createInstancesBuffer = function (capacity) {
  13301. var buffer = this._gl.createBuffer();
  13302. if (!buffer) {
  13303. throw new Error("Unable to create instance buffer");
  13304. }
  13305. buffer.capacity = capacity;
  13306. this.bindArrayBuffer(buffer);
  13307. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13308. return buffer;
  13309. };
  13310. /**
  13311. * Delete a webGL buffer used with instanciation
  13312. * @param buffer defines the webGL buffer to delete
  13313. */
  13314. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13315. this._gl.deleteBuffer(buffer);
  13316. };
  13317. /**
  13318. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13319. * @param instancesBuffer defines the webGL buffer to update and bind
  13320. * @param data defines the data to store in the buffer
  13321. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13322. */
  13323. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13324. this.bindArrayBuffer(instancesBuffer);
  13325. if (data) {
  13326. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13327. }
  13328. if (offsetLocations[0].index !== undefined) {
  13329. var stride = 0;
  13330. for (var i = 0; i < offsetLocations.length; i++) {
  13331. var ai = offsetLocations[i];
  13332. stride += ai.attributeSize * 4;
  13333. }
  13334. for (var i = 0; i < offsetLocations.length; i++) {
  13335. var ai = offsetLocations[i];
  13336. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13337. this._gl.enableVertexAttribArray(ai.index);
  13338. this._vertexAttribArraysEnabled[ai.index] = true;
  13339. }
  13340. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13341. this._gl.vertexAttribDivisor(ai.index, 1);
  13342. this._currentInstanceLocations.push(ai.index);
  13343. this._currentInstanceBuffers.push(instancesBuffer);
  13344. }
  13345. }
  13346. else {
  13347. for (var index = 0; index < 4; index++) {
  13348. var offsetLocation = offsetLocations[index];
  13349. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13350. this._gl.enableVertexAttribArray(offsetLocation);
  13351. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13352. }
  13353. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13354. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13355. this._currentInstanceLocations.push(offsetLocation);
  13356. this._currentInstanceBuffers.push(instancesBuffer);
  13357. }
  13358. }
  13359. };
  13360. /**
  13361. * Apply all cached states (depth, culling, stencil and alpha)
  13362. */
  13363. Engine.prototype.applyStates = function () {
  13364. this._depthCullingState.apply(this._gl);
  13365. this._stencilState.apply(this._gl);
  13366. this._alphaState.apply(this._gl);
  13367. };
  13368. /**
  13369. * Send a draw order
  13370. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13371. * @param indexStart defines the starting index
  13372. * @param indexCount defines the number of index to draw
  13373. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13374. */
  13375. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13376. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13377. };
  13378. /**
  13379. * Draw a list of points
  13380. * @param verticesStart defines the index of first vertex to draw
  13381. * @param verticesCount defines the count of vertices to draw
  13382. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13383. */
  13384. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13385. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13386. };
  13387. /**
  13388. * Draw a list of unindexed primitives
  13389. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13390. * @param verticesStart defines the index of first vertex to draw
  13391. * @param verticesCount defines the count of vertices to draw
  13392. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13393. */
  13394. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13395. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13396. };
  13397. /**
  13398. * Draw a list of indexed primitives
  13399. * @param fillMode defines the primitive to use
  13400. * @param indexStart defines the starting index
  13401. * @param indexCount defines the number of index to draw
  13402. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13403. */
  13404. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13405. // Apply states
  13406. this.applyStates();
  13407. this._drawCalls.addCount(1, false);
  13408. // Render
  13409. var drawMode = this._drawMode(fillMode);
  13410. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13411. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13412. if (instancesCount) {
  13413. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13414. }
  13415. else {
  13416. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13417. }
  13418. };
  13419. /**
  13420. * Draw a list of unindexed primitives
  13421. * @param fillMode defines the primitive to use
  13422. * @param verticesStart defines the index of first vertex to draw
  13423. * @param verticesCount defines the count of vertices to draw
  13424. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13425. */
  13426. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13427. // Apply states
  13428. this.applyStates();
  13429. this._drawCalls.addCount(1, false);
  13430. var drawMode = this._drawMode(fillMode);
  13431. if (instancesCount) {
  13432. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13433. }
  13434. else {
  13435. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13436. }
  13437. };
  13438. Engine.prototype._drawMode = function (fillMode) {
  13439. switch (fillMode) {
  13440. // Triangle views
  13441. case BABYLON.Material.TriangleFillMode:
  13442. return this._gl.TRIANGLES;
  13443. case BABYLON.Material.PointFillMode:
  13444. return this._gl.POINTS;
  13445. case BABYLON.Material.WireFrameFillMode:
  13446. return this._gl.LINES;
  13447. // Draw modes
  13448. case BABYLON.Material.PointListDrawMode:
  13449. return this._gl.POINTS;
  13450. case BABYLON.Material.LineListDrawMode:
  13451. return this._gl.LINES;
  13452. case BABYLON.Material.LineLoopDrawMode:
  13453. return this._gl.LINE_LOOP;
  13454. case BABYLON.Material.LineStripDrawMode:
  13455. return this._gl.LINE_STRIP;
  13456. case BABYLON.Material.TriangleStripDrawMode:
  13457. return this._gl.TRIANGLE_STRIP;
  13458. case BABYLON.Material.TriangleFanDrawMode:
  13459. return this._gl.TRIANGLE_FAN;
  13460. default:
  13461. return this._gl.TRIANGLES;
  13462. }
  13463. };
  13464. // Shaders
  13465. /** @ignore */
  13466. Engine.prototype._releaseEffect = function (effect) {
  13467. if (this._compiledEffects[effect._key]) {
  13468. delete this._compiledEffects[effect._key];
  13469. this._deleteProgram(effect.getProgram());
  13470. }
  13471. };
  13472. /** @ignore */
  13473. Engine.prototype._deleteProgram = function (program) {
  13474. if (program) {
  13475. program.__SPECTOR_rebuildProgram = null;
  13476. if (program.transformFeedback) {
  13477. this.deleteTransformFeedback(program.transformFeedback);
  13478. program.transformFeedback = null;
  13479. }
  13480. this._gl.deleteProgram(program);
  13481. }
  13482. };
  13483. /**
  13484. * Create a new effect (used to store vertex/fragment shaders)
  13485. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13486. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13487. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13488. * @param samplers defines an array of string used to represent textures
  13489. * @param defines defines the string containing the defines to use to compile the shaders
  13490. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13491. * @param onCompiled defines a function to call when the effect creation is successful
  13492. * @param onError defines a function to call when the effect creation has failed
  13493. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13494. * @returns the new Effect
  13495. */
  13496. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13497. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13498. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13499. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13500. if (this._compiledEffects[name]) {
  13501. var compiledEffect = this._compiledEffects[name];
  13502. if (onCompiled && compiledEffect.isReady()) {
  13503. onCompiled(compiledEffect);
  13504. }
  13505. return compiledEffect;
  13506. }
  13507. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13508. effect._key = name;
  13509. this._compiledEffects[name] = effect;
  13510. return effect;
  13511. };
  13512. /**
  13513. * Create an effect to use with particle systems
  13514. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13515. * @param uniformsNames defines a list of attribute names
  13516. * @param samplers defines an array of string used to represent textures
  13517. * @param defines defines the string containing the defines to use to compile the shaders
  13518. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13519. * @param onCompiled defines a function to call when the effect creation is successful
  13520. * @param onError defines a function to call when the effect creation has failed
  13521. * @returns the new Effect
  13522. */
  13523. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13524. if (uniformsNames === void 0) { uniformsNames = []; }
  13525. if (samplers === void 0) { samplers = []; }
  13526. if (defines === void 0) { defines = ""; }
  13527. return this.createEffect({
  13528. vertex: "particles",
  13529. fragmentElement: fragmentName
  13530. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13531. };
  13532. /**
  13533. * Directly creates a webGL program
  13534. * @param vertexCode defines the vertex shader code to use
  13535. * @param fragmentCode defines the fragment shader code to use
  13536. * @param context defines the webGL context to use (if not set, the current one will be used)
  13537. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13538. * @returns the new webGL program
  13539. */
  13540. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13541. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13542. context = context || this._gl;
  13543. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13544. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13545. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13546. };
  13547. /**
  13548. * Creates a webGL program
  13549. * @param vertexCode defines the vertex shader code to use
  13550. * @param fragmentCode defines the fragment shader code to use
  13551. * @param defines defines the string containing the defines to use to compile the shaders
  13552. * @param context defines the webGL context to use (if not set, the current one will be used)
  13553. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13554. * @returns the new webGL program
  13555. */
  13556. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13557. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13558. context = context || this._gl;
  13559. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13560. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13561. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13562. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13563. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13564. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13565. return program;
  13566. };
  13567. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13568. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13569. var shaderProgram = context.createProgram();
  13570. if (!shaderProgram) {
  13571. throw new Error("Unable to create program");
  13572. }
  13573. context.attachShader(shaderProgram, vertexShader);
  13574. context.attachShader(shaderProgram, fragmentShader);
  13575. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13576. var transformFeedback = this.createTransformFeedback();
  13577. this.bindTransformFeedback(transformFeedback);
  13578. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13579. shaderProgram.transformFeedback = transformFeedback;
  13580. }
  13581. context.linkProgram(shaderProgram);
  13582. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13583. this.bindTransformFeedback(null);
  13584. }
  13585. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13586. if (!linked) {
  13587. context.validateProgram(shaderProgram);
  13588. var error = context.getProgramInfoLog(shaderProgram);
  13589. if (error) {
  13590. throw new Error(error);
  13591. }
  13592. }
  13593. context.deleteShader(vertexShader);
  13594. context.deleteShader(fragmentShader);
  13595. return shaderProgram;
  13596. };
  13597. /**
  13598. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13599. * @param shaderProgram defines the webGL program to use
  13600. * @param uniformsNames defines the list of uniform names
  13601. * @returns an array of webGL uniform locations
  13602. */
  13603. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13604. var results = new Array();
  13605. for (var index = 0; index < uniformsNames.length; index++) {
  13606. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13607. }
  13608. return results;
  13609. };
  13610. /**
  13611. * Gets the lsit of active attributes for a given webGL program
  13612. * @param shaderProgram defines the webGL program to use
  13613. * @param attributesNames defines the list of attribute names to get
  13614. * @returns an array of indices indicating the offset of each attribute
  13615. */
  13616. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13617. var results = [];
  13618. for (var index = 0; index < attributesNames.length; index++) {
  13619. try {
  13620. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13621. }
  13622. catch (e) {
  13623. results.push(-1);
  13624. }
  13625. }
  13626. return results;
  13627. };
  13628. /**
  13629. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13630. * @param effect defines the effect to activate
  13631. */
  13632. Engine.prototype.enableEffect = function (effect) {
  13633. if (!effect) {
  13634. return;
  13635. }
  13636. // Use program
  13637. this.bindSamplers(effect);
  13638. this._currentEffect = effect;
  13639. if (effect.onBind) {
  13640. effect.onBind(effect);
  13641. }
  13642. effect.onBindObservable.notifyObservers(effect);
  13643. };
  13644. /**
  13645. * Set the value of an uniform to an array of int32
  13646. * @param uniform defines the webGL uniform location where to store the value
  13647. * @param array defines the array of int32 to store
  13648. */
  13649. Engine.prototype.setIntArray = function (uniform, array) {
  13650. if (!uniform)
  13651. return;
  13652. this._gl.uniform1iv(uniform, array);
  13653. };
  13654. /**
  13655. * Set the value of an uniform to an array of int32 (stored as vec2)
  13656. * @param uniform defines the webGL uniform location where to store the value
  13657. * @param array defines the array of int32 to store
  13658. */
  13659. Engine.prototype.setIntArray2 = function (uniform, array) {
  13660. if (!uniform || array.length % 2 !== 0)
  13661. return;
  13662. this._gl.uniform2iv(uniform, array);
  13663. };
  13664. /**
  13665. * Set the value of an uniform to an array of int32 (stored as vec3)
  13666. * @param uniform defines the webGL uniform location where to store the value
  13667. * @param array defines the array of int32 to store
  13668. */
  13669. Engine.prototype.setIntArray3 = function (uniform, array) {
  13670. if (!uniform || array.length % 3 !== 0)
  13671. return;
  13672. this._gl.uniform3iv(uniform, array);
  13673. };
  13674. /**
  13675. * Set the value of an uniform to an array of int32 (stored as vec4)
  13676. * @param uniform defines the webGL uniform location where to store the value
  13677. * @param array defines the array of int32 to store
  13678. */
  13679. Engine.prototype.setIntArray4 = function (uniform, array) {
  13680. if (!uniform || array.length % 4 !== 0)
  13681. return;
  13682. this._gl.uniform4iv(uniform, array);
  13683. };
  13684. /**
  13685. * Set the value of an uniform to an array of float32
  13686. * @param uniform defines the webGL uniform location where to store the value
  13687. * @param array defines the array of float32 to store
  13688. */
  13689. Engine.prototype.setFloatArray = function (uniform, array) {
  13690. if (!uniform)
  13691. return;
  13692. this._gl.uniform1fv(uniform, array);
  13693. };
  13694. /**
  13695. * Set the value of an uniform to an array of float32 (stored as vec2)
  13696. * @param uniform defines the webGL uniform location where to store the value
  13697. * @param array defines the array of float32 to store
  13698. */
  13699. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13700. if (!uniform || array.length % 2 !== 0)
  13701. return;
  13702. this._gl.uniform2fv(uniform, array);
  13703. };
  13704. /**
  13705. * Set the value of an uniform to an array of float32 (stored as vec3)
  13706. * @param uniform defines the webGL uniform location where to store the value
  13707. * @param array defines the array of float32 to store
  13708. */
  13709. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13710. if (!uniform || array.length % 3 !== 0)
  13711. return;
  13712. this._gl.uniform3fv(uniform, array);
  13713. };
  13714. /**
  13715. * Set the value of an uniform to an array of float32 (stored as vec4)
  13716. * @param uniform defines the webGL uniform location where to store the value
  13717. * @param array defines the array of float32 to store
  13718. */
  13719. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13720. if (!uniform || array.length % 4 !== 0)
  13721. return;
  13722. this._gl.uniform4fv(uniform, array);
  13723. };
  13724. /**
  13725. * Set the value of an uniform to an array of number
  13726. * @param uniform defines the webGL uniform location where to store the value
  13727. * @param array defines the array of number to store
  13728. */
  13729. Engine.prototype.setArray = function (uniform, array) {
  13730. if (!uniform)
  13731. return;
  13732. this._gl.uniform1fv(uniform, array);
  13733. };
  13734. /**
  13735. * Set the value of an uniform to an array of number (stored as vec2)
  13736. * @param uniform defines the webGL uniform location where to store the value
  13737. * @param array defines the array of number to store
  13738. */
  13739. Engine.prototype.setArray2 = function (uniform, array) {
  13740. if (!uniform || array.length % 2 !== 0)
  13741. return;
  13742. this._gl.uniform2fv(uniform, array);
  13743. };
  13744. /**
  13745. * Set the value of an uniform to an array of number (stored as vec3)
  13746. * @param uniform defines the webGL uniform location where to store the value
  13747. * @param array defines the array of number to store
  13748. */
  13749. Engine.prototype.setArray3 = function (uniform, array) {
  13750. if (!uniform || array.length % 3 !== 0)
  13751. return;
  13752. this._gl.uniform3fv(uniform, array);
  13753. };
  13754. /**
  13755. * Set the value of an uniform to an array of number (stored as vec4)
  13756. * @param uniform defines the webGL uniform location where to store the value
  13757. * @param array defines the array of number to store
  13758. */
  13759. Engine.prototype.setArray4 = function (uniform, array) {
  13760. if (!uniform || array.length % 4 !== 0)
  13761. return;
  13762. this._gl.uniform4fv(uniform, array);
  13763. };
  13764. /**
  13765. * Set the value of an uniform to an array of float32 (stored as matrices)
  13766. * @param uniform defines the webGL uniform location where to store the value
  13767. * @param matrices defines the array of float32 to store
  13768. */
  13769. Engine.prototype.setMatrices = function (uniform, matrices) {
  13770. if (!uniform)
  13771. return;
  13772. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13773. };
  13774. /**
  13775. * Set the value of an uniform to a matrix
  13776. * @param uniform defines the webGL uniform location where to store the value
  13777. * @param matrix defines the matrix to store
  13778. */
  13779. Engine.prototype.setMatrix = function (uniform, matrix) {
  13780. if (!uniform)
  13781. return;
  13782. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13783. };
  13784. /**
  13785. * Set the value of an uniform to a matrix (3x3)
  13786. * @param uniform defines the webGL uniform location where to store the value
  13787. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13788. */
  13789. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13790. if (!uniform)
  13791. return;
  13792. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13793. };
  13794. /**
  13795. * Set the value of an uniform to a matrix (2x2)
  13796. * @param uniform defines the webGL uniform location where to store the value
  13797. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13798. */
  13799. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13800. if (!uniform)
  13801. return;
  13802. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13803. };
  13804. /**
  13805. * Set the value of an uniform to a number (int)
  13806. * @param uniform defines the webGL uniform location where to store the value
  13807. * @param value defines the int number to store
  13808. */
  13809. Engine.prototype.setInt = function (uniform, value) {
  13810. if (!uniform)
  13811. return;
  13812. this._gl.uniform1i(uniform, value);
  13813. };
  13814. /**
  13815. * Set the value of an uniform to a number (float)
  13816. * @param uniform defines the webGL uniform location where to store the value
  13817. * @param value defines the float number to store
  13818. */
  13819. Engine.prototype.setFloat = function (uniform, value) {
  13820. if (!uniform)
  13821. return;
  13822. this._gl.uniform1f(uniform, value);
  13823. };
  13824. /**
  13825. * Set the value of an uniform to a vec2
  13826. * @param uniform defines the webGL uniform location where to store the value
  13827. * @param x defines the 1st component of the value
  13828. * @param y defines the 2nd component of the value
  13829. */
  13830. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13831. if (!uniform)
  13832. return;
  13833. this._gl.uniform2f(uniform, x, y);
  13834. };
  13835. /**
  13836. * Set the value of an uniform to a vec3
  13837. * @param uniform defines the webGL uniform location where to store the value
  13838. * @param x defines the 1st component of the value
  13839. * @param y defines the 2nd component of the value
  13840. * @param z defines the 3rd component of the value
  13841. */
  13842. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13843. if (!uniform)
  13844. return;
  13845. this._gl.uniform3f(uniform, x, y, z);
  13846. };
  13847. /**
  13848. * Set the value of an uniform to a boolean
  13849. * @param uniform defines the webGL uniform location where to store the value
  13850. * @param bool defines the boolean to store
  13851. */
  13852. Engine.prototype.setBool = function (uniform, bool) {
  13853. if (!uniform)
  13854. return;
  13855. this._gl.uniform1i(uniform, bool);
  13856. };
  13857. /**
  13858. * Set the value of an uniform to a vec4
  13859. * @param uniform defines the webGL uniform location where to store the value
  13860. * @param x defines the 1st component of the value
  13861. * @param y defines the 2nd component of the value
  13862. * @param z defines the 3rd component of the value
  13863. * @param w defines the 4th component of the value
  13864. */
  13865. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13866. if (!uniform)
  13867. return;
  13868. this._gl.uniform4f(uniform, x, y, z, w);
  13869. };
  13870. /**
  13871. * Set the value of an uniform to a Color3
  13872. * @param uniform defines the webGL uniform location where to store the value
  13873. * @param color3 defines the color to store
  13874. */
  13875. Engine.prototype.setColor3 = function (uniform, color3) {
  13876. if (!uniform)
  13877. return;
  13878. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13879. };
  13880. /**
  13881. * Set the value of an uniform to a Color3 and an alpha value
  13882. * @param uniform defines the webGL uniform location where to store the value
  13883. * @param color3 defines the color to store
  13884. * @param alpha defines the alpha component to store
  13885. */
  13886. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13887. if (!uniform)
  13888. return;
  13889. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13890. };
  13891. /**
  13892. * Sets a Color4 on a uniform variable
  13893. * @param uniform defines the uniform location
  13894. * @param color4 defines the value to be set
  13895. */
  13896. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13897. if (!uniform)
  13898. return;
  13899. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13900. };
  13901. // States
  13902. /**
  13903. * Set various states to the webGL context
  13904. * @param culling defines backface culling state
  13905. * @param zOffset defines the value to apply to zOffset (0 by default)
  13906. * @param force defines if states must be applied even if cache is up to date
  13907. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13908. */
  13909. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13910. if (zOffset === void 0) { zOffset = 0; }
  13911. if (reverseSide === void 0) { reverseSide = false; }
  13912. // Culling
  13913. if (this._depthCullingState.cull !== culling || force) {
  13914. this._depthCullingState.cull = culling;
  13915. }
  13916. // Cull face
  13917. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13918. if (this._depthCullingState.cullFace !== cullFace || force) {
  13919. this._depthCullingState.cullFace = cullFace;
  13920. }
  13921. // Z offset
  13922. this.setZOffset(zOffset);
  13923. // Front face
  13924. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13925. if (this._depthCullingState.frontFace !== frontFace || force) {
  13926. this._depthCullingState.frontFace = frontFace;
  13927. }
  13928. };
  13929. /**
  13930. * Set the z offset to apply to current rendering
  13931. * @param value defines the offset to apply
  13932. */
  13933. Engine.prototype.setZOffset = function (value) {
  13934. this._depthCullingState.zOffset = value;
  13935. };
  13936. /**
  13937. * Gets the current value of the zOffset
  13938. * @returns the current zOffset state
  13939. */
  13940. Engine.prototype.getZOffset = function () {
  13941. return this._depthCullingState.zOffset;
  13942. };
  13943. /**
  13944. * Enable or disable depth buffering
  13945. * @param enable defines the state to set
  13946. */
  13947. Engine.prototype.setDepthBuffer = function (enable) {
  13948. this._depthCullingState.depthTest = enable;
  13949. };
  13950. /**
  13951. * Gets a boolean indicating if depth writing is enabled
  13952. * @returns the current depth writing state
  13953. */
  13954. Engine.prototype.getDepthWrite = function () {
  13955. return this._depthCullingState.depthMask;
  13956. };
  13957. /**
  13958. * Enable or disable depth writing
  13959. * @param enable defines the state to set
  13960. */
  13961. Engine.prototype.setDepthWrite = function (enable) {
  13962. this._depthCullingState.depthMask = enable;
  13963. };
  13964. /**
  13965. * Enable or disable color writing
  13966. * @param enable defines the state to set
  13967. */
  13968. Engine.prototype.setColorWrite = function (enable) {
  13969. this._gl.colorMask(enable, enable, enable, enable);
  13970. this._colorWrite = enable;
  13971. };
  13972. /**
  13973. * Gets a boolean indicating if color writing is enabled
  13974. * @returns the current color writing state
  13975. */
  13976. Engine.prototype.getColorWrite = function () {
  13977. return this._colorWrite;
  13978. };
  13979. /**
  13980. * Sets alpha constants used by some alpha blending modes
  13981. * @param r defines the red component
  13982. * @param g defines the green component
  13983. * @param b defines the blue component
  13984. * @param a defines the alpha component
  13985. */
  13986. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  13987. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  13988. };
  13989. /**
  13990. * Sets the current alpha mode
  13991. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  13992. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  13993. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  13994. */
  13995. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  13996. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  13997. if (this._alphaMode === mode) {
  13998. return;
  13999. }
  14000. switch (mode) {
  14001. case Engine.ALPHA_DISABLE:
  14002. this._alphaState.alphaBlend = false;
  14003. break;
  14004. case Engine.ALPHA_PREMULTIPLIED:
  14005. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14006. this._alphaState.alphaBlend = true;
  14007. break;
  14008. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14009. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14010. this._alphaState.alphaBlend = true;
  14011. break;
  14012. case Engine.ALPHA_COMBINE:
  14013. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14014. this._alphaState.alphaBlend = true;
  14015. break;
  14016. case Engine.ALPHA_ONEONE:
  14017. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14018. this._alphaState.alphaBlend = true;
  14019. break;
  14020. case Engine.ALPHA_ADD:
  14021. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14022. this._alphaState.alphaBlend = true;
  14023. break;
  14024. case Engine.ALPHA_SUBTRACT:
  14025. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14026. this._alphaState.alphaBlend = true;
  14027. break;
  14028. case Engine.ALPHA_MULTIPLY:
  14029. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14030. this._alphaState.alphaBlend = true;
  14031. break;
  14032. case Engine.ALPHA_MAXIMIZED:
  14033. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14034. this._alphaState.alphaBlend = true;
  14035. break;
  14036. case Engine.ALPHA_INTERPOLATE:
  14037. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14038. this._alphaState.alphaBlend = true;
  14039. break;
  14040. case Engine.ALPHA_SCREENMODE:
  14041. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14042. this._alphaState.alphaBlend = true;
  14043. break;
  14044. }
  14045. if (!noDepthWriteChange) {
  14046. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14047. }
  14048. this._alphaMode = mode;
  14049. };
  14050. /**
  14051. * Gets the current alpha mode
  14052. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14053. * @returns the current alpha mode
  14054. */
  14055. Engine.prototype.getAlphaMode = function () {
  14056. return this._alphaMode;
  14057. };
  14058. // Textures
  14059. /**
  14060. * Force the entire cache to be cleared
  14061. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14062. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14063. */
  14064. Engine.prototype.wipeCaches = function (bruteForce) {
  14065. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14066. return;
  14067. }
  14068. this._currentEffect = null;
  14069. if (bruteForce) {
  14070. this.resetTextureCache();
  14071. this._currentProgram = null;
  14072. this._stencilState.reset();
  14073. this._depthCullingState.reset();
  14074. this.setDepthFunctionToLessOrEqual();
  14075. this._alphaState.reset();
  14076. }
  14077. this._resetVertexBufferBinding();
  14078. this._cachedIndexBuffer = null;
  14079. this._cachedEffectForVertexBuffers = null;
  14080. this._unbindVertexArrayObject();
  14081. this.bindIndexBuffer(null);
  14082. };
  14083. /**
  14084. * Set the compressed texture format to use, based on the formats you have, and the formats
  14085. * supported by the hardware / browser.
  14086. *
  14087. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14088. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14089. * to API arguments needed to compressed textures. This puts the burden on the container
  14090. * generator to house the arcane code for determining these for current & future formats.
  14091. *
  14092. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14093. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14094. *
  14095. * Note: The result of this call is not taken into account when a texture is base64.
  14096. *
  14097. * @param formatsAvailable defines the list of those format families you have created
  14098. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14099. *
  14100. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14101. * @returns The extension selected.
  14102. */
  14103. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14104. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14105. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14106. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14107. return this._textureFormatInUse = this._texturesSupported[i];
  14108. }
  14109. }
  14110. }
  14111. // actively set format to nothing, to allow this to be called more than once
  14112. // and possibly fail the 2nd time
  14113. this._textureFormatInUse = null;
  14114. return null;
  14115. };
  14116. /** @ignore */
  14117. Engine.prototype._createTexture = function () {
  14118. var texture = this._gl.createTexture();
  14119. if (!texture) {
  14120. throw new Error("Unable to create texture");
  14121. }
  14122. return texture;
  14123. };
  14124. /**
  14125. * Usually called from BABYLON.Texture.ts.
  14126. * Passed information to create a WebGLTexture
  14127. * @param urlArg defines a value which contains one of the following:
  14128. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14129. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14130. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14131. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14132. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14133. * @param scene needed for loading to the correct scene
  14134. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14135. * @param onLoad optional callback to be called upon successful completion
  14136. * @param onError optional callback to be called upon failure
  14137. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14138. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14139. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14140. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14141. */
  14142. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14143. var _this = this;
  14144. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14145. if (onLoad === void 0) { onLoad = null; }
  14146. if (onError === void 0) { onError = null; }
  14147. if (buffer === void 0) { buffer = null; }
  14148. if (fallback === void 0) { fallback = null; }
  14149. if (format === void 0) { format = null; }
  14150. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14151. var fromData = url.substr(0, 5) === "data:";
  14152. var fromBlob = url.substr(0, 5) === "blob:";
  14153. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14154. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14155. // establish the file extension, if possible
  14156. var lastDot = url.lastIndexOf('.');
  14157. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14158. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14159. var isTGA = (extension.indexOf(".tga") === 0);
  14160. // determine if a ktx file should be substituted
  14161. var isKTX = false;
  14162. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14163. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14164. isKTX = true;
  14165. }
  14166. if (scene) {
  14167. scene._addPendingData(texture);
  14168. }
  14169. texture.url = url;
  14170. texture.generateMipMaps = !noMipmap;
  14171. texture.samplingMode = samplingMode;
  14172. texture.invertY = invertY;
  14173. if (!this._doNotHandleContextLost) {
  14174. // Keep a link to the buffer only if we plan to handle context lost
  14175. texture._buffer = buffer;
  14176. }
  14177. var onLoadObserver = null;
  14178. if (onLoad && !fallback) {
  14179. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14180. }
  14181. if (!fallback)
  14182. this._internalTexturesCache.push(texture);
  14183. var onerror = function (message, exception) {
  14184. if (scene) {
  14185. scene._removePendingData(texture);
  14186. }
  14187. if (onLoadObserver) {
  14188. texture.onLoadedObservable.remove(onLoadObserver);
  14189. }
  14190. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14191. if (isKTX) {
  14192. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14193. }
  14194. else if (BABYLON.Tools.UseFallbackTexture) {
  14195. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14196. }
  14197. if (onError) {
  14198. onError(message || "Unknown error", exception);
  14199. }
  14200. };
  14201. var callback = null;
  14202. // processing for non-image formats
  14203. if (isKTX || isTGA || isDDS) {
  14204. if (isKTX) {
  14205. callback = function (data) {
  14206. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14207. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14208. ktx.uploadLevels(_this._gl, !noMipmap);
  14209. return false;
  14210. }, samplingMode);
  14211. };
  14212. }
  14213. else if (isTGA) {
  14214. callback = function (arrayBuffer) {
  14215. var data = new Uint8Array(arrayBuffer);
  14216. var header = BABYLON.TGATools.GetTGAHeader(data);
  14217. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14218. BABYLON.TGATools.UploadContent(_this._gl, data);
  14219. return false;
  14220. }, samplingMode);
  14221. };
  14222. }
  14223. else if (isDDS) {
  14224. callback = function (data) {
  14225. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14226. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14227. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14228. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14229. return false;
  14230. }, samplingMode);
  14231. };
  14232. }
  14233. if (!buffer) {
  14234. this._loadFile(url, function (data) {
  14235. if (callback) {
  14236. callback(data);
  14237. }
  14238. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14239. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14240. });
  14241. }
  14242. else {
  14243. if (callback) {
  14244. callback(buffer);
  14245. }
  14246. }
  14247. // image format processing
  14248. }
  14249. else {
  14250. var onload = function (img) {
  14251. if (fromBlob && !_this._doNotHandleContextLost) {
  14252. // We need to store the image if we need to rebuild the texture
  14253. // in case of a webgl context lost
  14254. texture._buffer = img;
  14255. }
  14256. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14257. var gl = _this._gl;
  14258. var isPot = (img.width === potWidth && img.height === potHeight);
  14259. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14260. if (isPot) {
  14261. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14262. return false;
  14263. }
  14264. // Using shaders to rescale because canvas.drawImage is lossy
  14265. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14266. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14267. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14271. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14272. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14273. _this._releaseTexture(source);
  14274. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14275. continuationCallback();
  14276. });
  14277. return true;
  14278. }, samplingMode);
  14279. };
  14280. if (!fromData || isBase64)
  14281. if (buffer instanceof HTMLImageElement) {
  14282. onload(buffer);
  14283. }
  14284. else {
  14285. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14286. }
  14287. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14288. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14289. else
  14290. onload(buffer);
  14291. }
  14292. return texture;
  14293. };
  14294. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14295. var _this = this;
  14296. var rtt = this.createRenderTargetTexture({
  14297. width: destination.width,
  14298. height: destination.height,
  14299. }, {
  14300. generateMipMaps: false,
  14301. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14302. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14303. generateDepthBuffer: false,
  14304. generateStencilBuffer: false
  14305. });
  14306. if (!this._rescalePostProcess) {
  14307. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14308. }
  14309. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14310. _this._rescalePostProcess.onApply = function (effect) {
  14311. effect._bindTexture("textureSampler", source);
  14312. };
  14313. var hostingScene = scene;
  14314. if (!hostingScene) {
  14315. hostingScene = _this.scenes[_this.scenes.length - 1];
  14316. }
  14317. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14318. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14319. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14320. _this.unBindFramebuffer(rtt);
  14321. _this._releaseTexture(rtt);
  14322. if (onComplete) {
  14323. onComplete();
  14324. }
  14325. });
  14326. };
  14327. /**
  14328. * Update a raw texture
  14329. * @param texture defines the texture to update
  14330. * @param data defines the data to store in the texture
  14331. * @param format defines the format of the data
  14332. * @param invertY defines if data must be stored with Y axis inverted
  14333. * @param compression defines the compression used (null by default)
  14334. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14335. */
  14336. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14337. if (compression === void 0) { compression = null; }
  14338. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14339. if (!texture) {
  14340. return;
  14341. }
  14342. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14343. var internalFormat = this._getInternalFormat(format);
  14344. var textureType = this._getWebGLTextureType(type);
  14345. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14346. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14347. if (!this._doNotHandleContextLost) {
  14348. texture._bufferView = data;
  14349. texture.format = format;
  14350. texture.type = type;
  14351. texture.invertY = invertY;
  14352. texture._compression = compression;
  14353. }
  14354. if (texture.width % 4 !== 0) {
  14355. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14356. }
  14357. if (compression && data) {
  14358. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14359. }
  14360. else {
  14361. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14362. }
  14363. if (texture.generateMipMaps) {
  14364. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14365. }
  14366. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14367. // this.resetTextureCache();
  14368. texture.isReady = true;
  14369. };
  14370. /**
  14371. * Creates a raw texture
  14372. * @param data defines the data to store in the texture
  14373. * @param width defines the width of the texture
  14374. * @param height defines the height of the texture
  14375. * @param format defines the format of the data
  14376. * @param generateMipMaps defines if the engine should generate the mip levels
  14377. * @param invertY defines if data must be stored with Y axis inverted
  14378. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14379. * @param compression defines the compression used (null by default)
  14380. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14381. * @returns the raw texture inside an InternalTexture
  14382. */
  14383. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14384. if (compression === void 0) { compression = null; }
  14385. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14386. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14387. texture.baseWidth = width;
  14388. texture.baseHeight = height;
  14389. texture.width = width;
  14390. texture.height = height;
  14391. texture.format = format;
  14392. texture.generateMipMaps = generateMipMaps;
  14393. texture.samplingMode = samplingMode;
  14394. texture.invertY = invertY;
  14395. texture._compression = compression;
  14396. texture.type = type;
  14397. if (!this._doNotHandleContextLost) {
  14398. texture._bufferView = data;
  14399. }
  14400. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14401. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14402. // Filters
  14403. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14404. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14405. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14406. if (generateMipMaps) {
  14407. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14408. }
  14409. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14410. this._internalTexturesCache.push(texture);
  14411. return texture;
  14412. };
  14413. /**
  14414. * Creates a dynamic texture
  14415. * @param width defines the width of the texture
  14416. * @param height defines the height of the texture
  14417. * @param generateMipMaps defines if the engine should generate the mip levels
  14418. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14419. * @returns the dynamic texture inside an InternalTexture
  14420. */
  14421. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14422. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14423. texture.baseWidth = width;
  14424. texture.baseHeight = height;
  14425. if (generateMipMaps) {
  14426. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14427. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14428. }
  14429. // this.resetTextureCache();
  14430. texture.width = width;
  14431. texture.height = height;
  14432. texture.isReady = false;
  14433. texture.generateMipMaps = generateMipMaps;
  14434. texture.samplingMode = samplingMode;
  14435. this.updateTextureSamplingMode(samplingMode, texture);
  14436. this._internalTexturesCache.push(texture);
  14437. return texture;
  14438. };
  14439. /**
  14440. * Update the sampling mode of a given texture
  14441. * @param samplingMode defines the required sampling mode
  14442. * @param texture defines the texture to update
  14443. */
  14444. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14445. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14446. if (texture.isCube) {
  14447. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14448. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14449. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14450. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14451. }
  14452. else if (texture.is3D) {
  14453. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14454. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14455. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14456. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14457. }
  14458. else {
  14459. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14460. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14461. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14462. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14463. }
  14464. texture.samplingMode = samplingMode;
  14465. };
  14466. /**
  14467. * Update the content of a dynamic texture
  14468. * @param texture defines the texture to update
  14469. * @param canvas defines the canvas containing the source
  14470. * @param invertY defines if data must be stored with Y axis inverted
  14471. * @param premulAlpha defines if alpha is stored as premultiplied
  14472. * @param format defines the format of the data
  14473. */
  14474. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14475. if (premulAlpha === void 0) { premulAlpha = false; }
  14476. if (!texture) {
  14477. return;
  14478. }
  14479. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14480. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14481. if (premulAlpha) {
  14482. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14483. }
  14484. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14485. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14486. if (texture.generateMipMaps) {
  14487. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14488. }
  14489. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14490. if (premulAlpha) {
  14491. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14492. }
  14493. texture.isReady = true;
  14494. };
  14495. /**
  14496. * Update a video texture
  14497. * @param texture defines the texture to update
  14498. * @param video defines the video element to use
  14499. * @param invertY defines if data must be stored with Y axis inverted
  14500. */
  14501. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14502. if (!texture || texture._isDisabled) {
  14503. return;
  14504. }
  14505. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14506. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14507. try {
  14508. // Testing video texture support
  14509. if (this._videoTextureSupported === undefined) {
  14510. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14511. if (this._gl.getError() !== 0) {
  14512. this._videoTextureSupported = false;
  14513. }
  14514. else {
  14515. this._videoTextureSupported = true;
  14516. }
  14517. }
  14518. // Copy video through the current working canvas if video texture is not supported
  14519. if (!this._videoTextureSupported) {
  14520. if (!texture._workingCanvas) {
  14521. texture._workingCanvas = document.createElement("canvas");
  14522. var context = texture._workingCanvas.getContext("2d");
  14523. if (!context) {
  14524. throw new Error("Unable to get 2d context");
  14525. }
  14526. texture._workingContext = context;
  14527. texture._workingCanvas.width = texture.width;
  14528. texture._workingCanvas.height = texture.height;
  14529. }
  14530. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14531. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14532. }
  14533. else {
  14534. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14535. }
  14536. if (texture.generateMipMaps) {
  14537. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14538. }
  14539. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14540. // this.resetTextureCache();
  14541. texture.isReady = true;
  14542. }
  14543. catch (ex) {
  14544. // Something unexpected
  14545. // Let's disable the texture
  14546. texture._isDisabled = true;
  14547. }
  14548. };
  14549. /**
  14550. * Updates a depth texture Comparison Mode and Function.
  14551. * If the comparison Function is equal to 0, the mode will be set to none.
  14552. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14553. * @param texture The texture to set the comparison function for
  14554. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14555. */
  14556. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14557. if (this.webGLVersion === 1) {
  14558. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14559. return;
  14560. }
  14561. var gl = this._gl;
  14562. if (texture.isCube) {
  14563. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14564. if (comparisonFunction === 0) {
  14565. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14567. }
  14568. else {
  14569. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14571. }
  14572. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14573. }
  14574. else {
  14575. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14576. if (comparisonFunction === 0) {
  14577. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14578. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14579. }
  14580. else {
  14581. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14582. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14583. }
  14584. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14585. }
  14586. texture._comparisonFunction = comparisonFunction;
  14587. };
  14588. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14589. var width = size.width || size;
  14590. var height = size.height || size;
  14591. internalTexture.baseWidth = width;
  14592. internalTexture.baseHeight = height;
  14593. internalTexture.width = width;
  14594. internalTexture.height = height;
  14595. internalTexture.isReady = true;
  14596. internalTexture.samples = 1;
  14597. internalTexture.generateMipMaps = false;
  14598. internalTexture._generateDepthBuffer = true;
  14599. internalTexture._generateStencilBuffer = generateStencil;
  14600. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14601. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14602. internalTexture._comparisonFunction = comparisonFunction;
  14603. var gl = this._gl;
  14604. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14605. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14606. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14607. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14608. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14609. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14610. if (comparisonFunction === 0) {
  14611. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14612. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14613. }
  14614. else {
  14615. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14616. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14617. }
  14618. };
  14619. /**
  14620. * Creates a depth stencil texture.
  14621. * This is only available in WebGL 2 or with the depth texture extension available.
  14622. * @param size The size of face edge in the texture.
  14623. * @param options The options defining the texture.
  14624. * @returns The texture
  14625. */
  14626. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14627. if (options.isCube) {
  14628. var width = size.width || size;
  14629. return this._createDepthStencilCubeTexture(width, options);
  14630. }
  14631. else {
  14632. return this._createDepthStencilTexture(size, options);
  14633. }
  14634. };
  14635. /**
  14636. * Creates a depth stencil texture.
  14637. * This is only available in WebGL 2 or with the depth texture extension available.
  14638. * @param size The size of face edge in the texture.
  14639. * @param options The options defining the texture.
  14640. * @returns The texture
  14641. */
  14642. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14643. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14644. if (!this._caps.depthTextureExtension) {
  14645. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14646. return internalTexture;
  14647. }
  14648. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14649. var gl = this._gl;
  14650. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14651. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14652. if (this.webGLVersion > 1) {
  14653. if (internalOptions.generateStencil) {
  14654. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14655. }
  14656. else {
  14657. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14658. }
  14659. }
  14660. else {
  14661. if (internalOptions.generateStencil) {
  14662. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14663. }
  14664. else {
  14665. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14666. }
  14667. }
  14668. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14669. return internalTexture;
  14670. };
  14671. /**
  14672. * Creates a depth stencil cube texture.
  14673. * This is only available in WebGL 2.
  14674. * @param size The size of face edge in the cube texture.
  14675. * @param options The options defining the cube texture.
  14676. * @returns The cube texture
  14677. */
  14678. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14679. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14680. internalTexture.isCube = true;
  14681. if (this.webGLVersion === 1) {
  14682. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14683. return internalTexture;
  14684. }
  14685. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14686. var gl = this._gl;
  14687. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14688. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14689. // Create the depth/stencil buffer
  14690. for (var face = 0; face < 6; face++) {
  14691. if (internalOptions.generateStencil) {
  14692. 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);
  14693. }
  14694. else {
  14695. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14696. }
  14697. }
  14698. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14699. return internalTexture;
  14700. };
  14701. /**
  14702. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14703. * @param renderTarget The render target to set the frame buffer for
  14704. */
  14705. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14706. // Create the framebuffer
  14707. var internalTexture = renderTarget.getInternalTexture();
  14708. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14709. return;
  14710. }
  14711. var gl = this._gl;
  14712. var depthStencilTexture = renderTarget.depthStencilTexture;
  14713. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14714. if (depthStencilTexture.isCube) {
  14715. if (depthStencilTexture._generateStencilBuffer) {
  14716. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14717. }
  14718. else {
  14719. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14720. }
  14721. }
  14722. else {
  14723. if (depthStencilTexture._generateStencilBuffer) {
  14724. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14725. }
  14726. else {
  14727. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14728. }
  14729. }
  14730. this.bindUnboundFramebuffer(null);
  14731. };
  14732. /**
  14733. * Creates a new render target texture
  14734. * @param size defines the size of the texture
  14735. * @param options defines the options used to create the texture
  14736. * @returns a new render target texture stored in an InternalTexture
  14737. */
  14738. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14739. var fullOptions = new RenderTargetCreationOptions();
  14740. if (options !== undefined && typeof options === "object") {
  14741. fullOptions.generateMipMaps = options.generateMipMaps;
  14742. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14743. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14744. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14745. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14746. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14747. }
  14748. else {
  14749. fullOptions.generateMipMaps = options;
  14750. fullOptions.generateDepthBuffer = true;
  14751. fullOptions.generateStencilBuffer = false;
  14752. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14753. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14754. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14755. }
  14756. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14757. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14758. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14759. }
  14760. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14761. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14762. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14763. }
  14764. var gl = this._gl;
  14765. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14766. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14767. var width = size.width || size;
  14768. var height = size.height || size;
  14769. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14770. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14771. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14772. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14773. }
  14774. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14775. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14776. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14777. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14778. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14779. // Create the framebuffer
  14780. var framebuffer = gl.createFramebuffer();
  14781. this.bindUnboundFramebuffer(framebuffer);
  14782. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14783. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14784. if (fullOptions.generateMipMaps) {
  14785. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14786. }
  14787. // Unbind
  14788. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14789. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14790. this.bindUnboundFramebuffer(null);
  14791. texture._framebuffer = framebuffer;
  14792. texture.baseWidth = width;
  14793. texture.baseHeight = height;
  14794. texture.width = width;
  14795. texture.height = height;
  14796. texture.isReady = true;
  14797. texture.samples = 1;
  14798. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  14799. texture.samplingMode = fullOptions.samplingMode;
  14800. texture.type = fullOptions.type;
  14801. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14802. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  14803. // this.resetTextureCache();
  14804. this._internalTexturesCache.push(texture);
  14805. return texture;
  14806. };
  14807. /**
  14808. * Create a multi render target texture
  14809. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  14810. * @param size defines the size of the texture
  14811. * @param options defines the creation options
  14812. * @returns the cube texture as an InternalTexture
  14813. */
  14814. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  14815. var generateMipMaps = false;
  14816. var generateDepthBuffer = true;
  14817. var generateStencilBuffer = false;
  14818. var generateDepthTexture = false;
  14819. var textureCount = 1;
  14820. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  14821. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14822. var types = new Array();
  14823. var samplingModes = new Array();
  14824. if (options !== undefined) {
  14825. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  14826. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14827. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  14828. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  14829. textureCount = options.textureCount || 1;
  14830. if (options.types) {
  14831. types = options.types;
  14832. }
  14833. if (options.samplingModes) {
  14834. samplingModes = options.samplingModes;
  14835. }
  14836. }
  14837. var gl = this._gl;
  14838. // Create the framebuffer
  14839. var framebuffer = gl.createFramebuffer();
  14840. this.bindUnboundFramebuffer(framebuffer);
  14841. var width = size.width || size;
  14842. var height = size.height || size;
  14843. var textures = [];
  14844. var attachments = [];
  14845. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  14846. for (var i = 0; i < textureCount; i++) {
  14847. var samplingMode = samplingModes[i] || defaultSamplingMode;
  14848. var type = types[i] || defaultType;
  14849. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14850. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14851. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14852. }
  14853. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14854. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14855. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14856. }
  14857. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14858. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14859. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14860. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14861. }
  14862. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14863. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14864. textures.push(texture);
  14865. attachments.push(attachment);
  14866. gl.activeTexture(gl["TEXTURE" + i]);
  14867. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  14868. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14871. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14872. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14873. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14874. if (generateMipMaps) {
  14875. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14876. }
  14877. // Unbind
  14878. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14879. texture._framebuffer = framebuffer;
  14880. texture._depthStencilBuffer = depthStencilBuffer;
  14881. texture.baseWidth = width;
  14882. texture.baseHeight = height;
  14883. texture.width = width;
  14884. texture.height = height;
  14885. texture.isReady = true;
  14886. texture.samples = 1;
  14887. texture.generateMipMaps = generateMipMaps;
  14888. texture.samplingMode = samplingMode;
  14889. texture.type = type;
  14890. texture._generateDepthBuffer = generateDepthBuffer;
  14891. texture._generateStencilBuffer = generateStencilBuffer;
  14892. texture._attachments = attachments;
  14893. this._internalTexturesCache.push(texture);
  14894. }
  14895. if (generateDepthTexture && this._caps.depthTextureExtension) {
  14896. // Depth texture
  14897. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14898. gl.activeTexture(gl.TEXTURE0);
  14899. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  14900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14901. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14902. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14903. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14904. 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);
  14905. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  14906. depthTexture._framebuffer = framebuffer;
  14907. depthTexture.baseWidth = width;
  14908. depthTexture.baseHeight = height;
  14909. depthTexture.width = width;
  14910. depthTexture.height = height;
  14911. depthTexture.isReady = true;
  14912. depthTexture.samples = 1;
  14913. depthTexture.generateMipMaps = generateMipMaps;
  14914. depthTexture.samplingMode = gl.NEAREST;
  14915. depthTexture._generateDepthBuffer = generateDepthBuffer;
  14916. depthTexture._generateStencilBuffer = generateStencilBuffer;
  14917. textures.push(depthTexture);
  14918. this._internalTexturesCache.push(depthTexture);
  14919. }
  14920. gl.drawBuffers(attachments);
  14921. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14922. this.bindUnboundFramebuffer(null);
  14923. this.resetTextureCache();
  14924. return textures;
  14925. };
  14926. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  14927. if (samples === void 0) { samples = 1; }
  14928. var depthStencilBuffer = null;
  14929. var gl = this._gl;
  14930. // Create the depth/stencil buffer
  14931. if (generateStencilBuffer) {
  14932. depthStencilBuffer = gl.createRenderbuffer();
  14933. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  14934. if (samples > 1) {
  14935. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  14936. }
  14937. else {
  14938. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  14939. }
  14940. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  14941. }
  14942. else if (generateDepthBuffer) {
  14943. depthStencilBuffer = gl.createRenderbuffer();
  14944. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  14945. if (samples > 1) {
  14946. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  14947. }
  14948. else {
  14949. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  14950. }
  14951. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  14952. }
  14953. return depthStencilBuffer;
  14954. };
  14955. /**
  14956. * Updates the sample count of a render target texture
  14957. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  14958. * @param texture defines the texture to update
  14959. * @param samples defines the sample count to set
  14960. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  14961. */
  14962. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  14963. if (this.webGLVersion < 2 || !texture) {
  14964. return 1;
  14965. }
  14966. if (texture.samples === samples) {
  14967. return samples;
  14968. }
  14969. var gl = this._gl;
  14970. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  14971. // Dispose previous render buffers
  14972. if (texture._depthStencilBuffer) {
  14973. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14974. texture._depthStencilBuffer = null;
  14975. }
  14976. if (texture._MSAAFramebuffer) {
  14977. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14978. texture._MSAAFramebuffer = null;
  14979. }
  14980. if (texture._MSAARenderBuffer) {
  14981. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14982. texture._MSAARenderBuffer = null;
  14983. }
  14984. if (samples > 1) {
  14985. var framebuffer = gl.createFramebuffer();
  14986. if (!framebuffer) {
  14987. throw new Error("Unable to create multi sampled framebuffer");
  14988. }
  14989. texture._MSAAFramebuffer = framebuffer;
  14990. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  14991. var colorRenderbuffer = gl.createRenderbuffer();
  14992. if (!colorRenderbuffer) {
  14993. throw new Error("Unable to create multi sampled framebuffer");
  14994. }
  14995. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  14996. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14997. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  14998. texture._MSAARenderBuffer = colorRenderbuffer;
  14999. }
  15000. else {
  15001. this.bindUnboundFramebuffer(texture._framebuffer);
  15002. }
  15003. texture.samples = samples;
  15004. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15005. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15006. this.bindUnboundFramebuffer(null);
  15007. return samples;
  15008. };
  15009. /**
  15010. * Update the sample count for a given multiple render target texture
  15011. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15012. * @param textures defines the textures to update
  15013. * @param samples defines the sample count to set
  15014. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15015. */
  15016. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15017. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15018. return 1;
  15019. }
  15020. if (textures[0].samples === samples) {
  15021. return samples;
  15022. }
  15023. var gl = this._gl;
  15024. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15025. // Dispose previous render buffers
  15026. if (textures[0]._depthStencilBuffer) {
  15027. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15028. textures[0]._depthStencilBuffer = null;
  15029. }
  15030. if (textures[0]._MSAAFramebuffer) {
  15031. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15032. textures[0]._MSAAFramebuffer = null;
  15033. }
  15034. for (var i = 0; i < textures.length; i++) {
  15035. if (textures[i]._MSAARenderBuffer) {
  15036. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15037. textures[i]._MSAARenderBuffer = null;
  15038. }
  15039. }
  15040. if (samples > 1) {
  15041. var framebuffer = gl.createFramebuffer();
  15042. if (!framebuffer) {
  15043. throw new Error("Unable to create multi sampled framebuffer");
  15044. }
  15045. this.bindUnboundFramebuffer(framebuffer);
  15046. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15047. var attachments = [];
  15048. for (var i = 0; i < textures.length; i++) {
  15049. var texture = textures[i];
  15050. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15051. var colorRenderbuffer = gl.createRenderbuffer();
  15052. if (!colorRenderbuffer) {
  15053. throw new Error("Unable to create multi sampled framebuffer");
  15054. }
  15055. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15056. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15057. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15058. texture._MSAAFramebuffer = framebuffer;
  15059. texture._MSAARenderBuffer = colorRenderbuffer;
  15060. texture.samples = samples;
  15061. texture._depthStencilBuffer = depthStencilBuffer;
  15062. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15063. attachments.push(attachment);
  15064. }
  15065. gl.drawBuffers(attachments);
  15066. }
  15067. else {
  15068. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15069. }
  15070. this.bindUnboundFramebuffer(null);
  15071. return samples;
  15072. };
  15073. /** @ignore */
  15074. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15075. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15076. };
  15077. /** @ignore */
  15078. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15079. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15080. };
  15081. /**
  15082. * Creates a new render target cube texture
  15083. * @param size defines the size of the texture
  15084. * @param options defines the options used to create the texture
  15085. * @returns a new render target cube texture stored in an InternalTexture
  15086. */
  15087. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15088. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15089. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15090. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15091. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15092. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15093. }
  15094. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15095. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15096. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15097. }
  15098. var gl = this._gl;
  15099. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15100. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15101. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15102. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15103. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15104. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15105. }
  15106. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15107. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15108. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15109. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15110. for (var face = 0; face < 6; face++) {
  15111. 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);
  15112. }
  15113. // Create the framebuffer
  15114. var framebuffer = gl.createFramebuffer();
  15115. this.bindUnboundFramebuffer(framebuffer);
  15116. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15117. // MipMaps
  15118. if (fullOptions.generateMipMaps) {
  15119. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15120. }
  15121. // Unbind
  15122. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15123. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15124. this.bindUnboundFramebuffer(null);
  15125. texture._framebuffer = framebuffer;
  15126. texture.width = size;
  15127. texture.height = size;
  15128. texture.isReady = true;
  15129. texture.isCube = true;
  15130. texture.samples = 1;
  15131. texture.generateMipMaps = fullOptions.generateMipMaps;
  15132. texture.samplingMode = fullOptions.samplingMode;
  15133. texture.type = fullOptions.type;
  15134. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15135. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15136. this._internalTexturesCache.push(texture);
  15137. return texture;
  15138. };
  15139. /**
  15140. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15141. * @param rootUrl defines the url where the file to load is located
  15142. * @param scene defines the current scene
  15143. * @param scale defines scale to apply to the mip map selection
  15144. * @param offset defines offset to apply to the mip map selection
  15145. * @param onLoad defines an optional callback raised when the texture is loaded
  15146. * @param onError defines an optional callback raised if there is an issue to load the texture
  15147. * @param format defines the format of the data
  15148. * @param forcedExtension defines the extension to use to pick the right loader
  15149. * @returns the cube texture as an InternalTexture
  15150. */
  15151. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15152. var _this = this;
  15153. if (onLoad === void 0) { onLoad = null; }
  15154. if (onError === void 0) { onError = null; }
  15155. if (forcedExtension === void 0) { forcedExtension = null; }
  15156. var callback = function (loadData) {
  15157. if (!loadData) {
  15158. if (onLoad) {
  15159. onLoad(null);
  15160. }
  15161. return;
  15162. }
  15163. var texture = loadData.texture;
  15164. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15165. texture._lodGenerationScale = scale;
  15166. texture._lodGenerationOffset = offset;
  15167. if (_this._caps.textureLOD) {
  15168. // Do not add extra process if texture lod is supported.
  15169. if (onLoad) {
  15170. onLoad(texture);
  15171. }
  15172. return;
  15173. }
  15174. var mipSlices = 3;
  15175. var gl = _this._gl;
  15176. var width = loadData.width;
  15177. if (!width) {
  15178. return;
  15179. }
  15180. var textures = [];
  15181. for (var i = 0; i < mipSlices; i++) {
  15182. //compute LOD from even spacing in smoothness (matching shader calculation)
  15183. var smoothness = i / (mipSlices - 1);
  15184. var roughness = 1 - smoothness;
  15185. var minLODIndex = offset; // roughness = 0
  15186. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15187. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15188. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15189. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15190. glTextureFromLod.isCube = true;
  15191. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15192. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15193. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15194. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15195. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15196. if (loadData.isDDS) {
  15197. var info = loadData.info;
  15198. var data = loadData.data;
  15199. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15200. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15201. }
  15202. else {
  15203. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15204. }
  15205. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15206. // Wrap in a base texture for easy binding.
  15207. var lodTexture = new BABYLON.BaseTexture(scene);
  15208. lodTexture.isCube = true;
  15209. lodTexture._texture = glTextureFromLod;
  15210. glTextureFromLod.isReady = true;
  15211. textures.push(lodTexture);
  15212. }
  15213. texture._lodTextureHigh = textures[2];
  15214. texture._lodTextureMid = textures[1];
  15215. texture._lodTextureLow = textures[0];
  15216. if (onLoad) {
  15217. onLoad(texture);
  15218. }
  15219. };
  15220. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  15221. };
  15222. /**
  15223. * Creates a cube texture
  15224. * @param rootUrl defines the url where the files to load is located
  15225. * @param scene defines the current scene
  15226. * @param files defines the list of files to load (1 per face)
  15227. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15228. * @param onLoad defines an optional callback raised when the texture is loaded
  15229. * @param onError defines an optional callback raised if there is an issue to load the texture
  15230. * @param format defines the format of the data
  15231. * @param forcedExtension defines the extension to use to pick the right loader
  15232. * @returns the cube texture as an InternalTexture
  15233. */
  15234. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  15235. var _this = this;
  15236. if (onLoad === void 0) { onLoad = null; }
  15237. if (onError === void 0) { onError = null; }
  15238. if (forcedExtension === void 0) { forcedExtension = null; }
  15239. var gl = this._gl;
  15240. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15241. texture.isCube = true;
  15242. texture.url = rootUrl;
  15243. texture.generateMipMaps = !noMipmap;
  15244. if (!this._doNotHandleContextLost) {
  15245. texture._extension = forcedExtension;
  15246. texture._files = files;
  15247. }
  15248. var isKTX = false;
  15249. var isDDS = false;
  15250. var lastDot = rootUrl.lastIndexOf('.');
  15251. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15252. if (this._textureFormatInUse) {
  15253. extension = this._textureFormatInUse;
  15254. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15255. isKTX = true;
  15256. }
  15257. else {
  15258. isDDS = (extension === ".dds");
  15259. }
  15260. var onerror = function (request, exception) {
  15261. if (onError && request) {
  15262. onError(request.status + " " + request.statusText, exception);
  15263. }
  15264. };
  15265. if (isKTX) {
  15266. this._loadFile(rootUrl, function (data) {
  15267. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15268. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15269. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15270. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15271. ktx.uploadLevels(_this._gl, !noMipmap);
  15272. _this.setCubeMapTextureParams(gl, loadMipmap);
  15273. texture.width = ktx.pixelWidth;
  15274. texture.height = ktx.pixelHeight;
  15275. texture.isReady = true;
  15276. }, undefined, undefined, true, onerror);
  15277. }
  15278. else if (isDDS) {
  15279. if (files && files.length === 6) {
  15280. this._cascadeLoadFiles(scene, function (imgs) {
  15281. var info;
  15282. var loadMipmap = false;
  15283. var width = 0;
  15284. for (var index = 0; index < imgs.length; index++) {
  15285. var data = imgs[index];
  15286. info = BABYLON.DDSTools.GetDDSInfo(data);
  15287. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15288. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15289. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15290. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15291. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15292. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15293. }
  15294. texture.width = info.width;
  15295. texture.height = info.height;
  15296. texture.type = info.textureType;
  15297. width = info.width;
  15298. }
  15299. _this.setCubeMapTextureParams(gl, loadMipmap);
  15300. texture.isReady = true;
  15301. if (onLoad) {
  15302. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15303. }
  15304. }, files, onError);
  15305. }
  15306. else {
  15307. this._loadFile(rootUrl, function (data) {
  15308. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15309. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15310. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15311. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15312. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15313. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15314. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15315. }
  15316. _this.setCubeMapTextureParams(gl, loadMipmap);
  15317. texture.width = info.width;
  15318. texture.height = info.height;
  15319. texture.isReady = true;
  15320. texture.type = info.textureType;
  15321. if (onLoad) {
  15322. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15323. }
  15324. }, undefined, undefined, true, onerror);
  15325. }
  15326. }
  15327. else {
  15328. if (!files) {
  15329. throw new Error("Cannot load cubemap because files were not defined");
  15330. }
  15331. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15332. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15333. var height = width;
  15334. _this._prepareWorkingCanvas();
  15335. if (!_this._workingCanvas || !_this._workingContext) {
  15336. return;
  15337. }
  15338. _this._workingCanvas.width = width;
  15339. _this._workingCanvas.height = height;
  15340. var faces = [
  15341. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15342. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15343. ];
  15344. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15345. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15346. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15347. for (var index = 0; index < faces.length; index++) {
  15348. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15349. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15350. }
  15351. if (!noMipmap) {
  15352. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15353. }
  15354. _this.setCubeMapTextureParams(gl, !noMipmap);
  15355. texture.width = width;
  15356. texture.height = height;
  15357. texture.isReady = true;
  15358. if (format) {
  15359. texture.format = format;
  15360. }
  15361. texture.onLoadedObservable.notifyObservers(texture);
  15362. texture.onLoadedObservable.clear();
  15363. if (onLoad) {
  15364. onLoad();
  15365. }
  15366. }, files, onError);
  15367. }
  15368. this._internalTexturesCache.push(texture);
  15369. return texture;
  15370. };
  15371. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15373. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15374. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15375. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15376. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15377. // this.resetTextureCache();
  15378. };
  15379. /**
  15380. * Update a raw cube texture
  15381. * @param texture defines the texture to udpdate
  15382. * @param data defines the data to store
  15383. * @param format defines the data format
  15384. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15385. * @param invertY defines if data must be stored with Y axis inverted
  15386. * @param compression defines the compression used (null by default)
  15387. * @param level defines which level of the texture to update
  15388. */
  15389. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15390. if (compression === void 0) { compression = null; }
  15391. if (level === void 0) { level = 0; }
  15392. texture._bufferViewArray = data;
  15393. texture.format = format;
  15394. texture.type = type;
  15395. texture.invertY = invertY;
  15396. texture._compression = compression;
  15397. var gl = this._gl;
  15398. var textureType = this._getWebGLTextureType(type);
  15399. var internalFormat = this._getInternalFormat(format);
  15400. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15401. var needConversion = false;
  15402. if (internalFormat === gl.RGB) {
  15403. internalFormat = gl.RGBA;
  15404. needConversion = true;
  15405. }
  15406. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15407. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15408. if (texture.width % 4 !== 0) {
  15409. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15410. }
  15411. // Data are known to be in +X +Y +Z -X -Y -Z
  15412. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15413. var faceData = data[faceIndex];
  15414. if (compression) {
  15415. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15416. }
  15417. else {
  15418. if (needConversion) {
  15419. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15420. }
  15421. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15422. }
  15423. }
  15424. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15425. if (isPot && texture.generateMipMaps && level === 0) {
  15426. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15427. }
  15428. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15429. // this.resetTextureCache();
  15430. texture.isReady = true;
  15431. };
  15432. /**
  15433. * Creates a new raw cube texture
  15434. * @param data defines the array of data to use to create each face
  15435. * @param size defines the size of the textures
  15436. * @param format defines the format of the data
  15437. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15438. * @param generateMipMaps defines if the engine should generate the mip levels
  15439. * @param invertY defines if data must be stored with Y axis inverted
  15440. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15441. * @param compression defines the compression used (null by default)
  15442. * @returns the cube texture as an InternalTexture
  15443. */
  15444. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15445. if (compression === void 0) { compression = null; }
  15446. var gl = this._gl;
  15447. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15448. texture.isCube = true;
  15449. texture.generateMipMaps = generateMipMaps;
  15450. texture.format = format;
  15451. texture.type = type;
  15452. if (!this._doNotHandleContextLost) {
  15453. texture._bufferViewArray = data;
  15454. }
  15455. var textureType = this._getWebGLTextureType(type);
  15456. var internalFormat = this._getInternalFormat(format);
  15457. if (internalFormat === gl.RGB) {
  15458. internalFormat = gl.RGBA;
  15459. }
  15460. var width = size;
  15461. var height = width;
  15462. texture.width = width;
  15463. texture.height = height;
  15464. // Double check on POT to generate Mips.
  15465. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15466. if (!isPot) {
  15467. generateMipMaps = false;
  15468. }
  15469. // Upload data if needed. The texture won't be ready until then.
  15470. if (data) {
  15471. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15472. }
  15473. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15474. // Filters
  15475. if (data && generateMipMaps) {
  15476. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15477. }
  15478. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15479. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15480. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15481. }
  15482. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15483. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15484. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15485. }
  15486. else {
  15487. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15489. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15490. }
  15491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15492. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15493. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15494. return texture;
  15495. };
  15496. /**
  15497. * Creates a new raw cube texture from a specified url
  15498. * @param url defines the url where the data is located
  15499. * @param scene defines the current scene
  15500. * @param size defines the size of the textures
  15501. * @param format defines the format of the data
  15502. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15503. * @param noMipmap defines if the engine should avoid generating the mip levels
  15504. * @param callback defines a callback used to extract texture data from loaded data
  15505. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15506. * @param onLoad defines a callback called when texture is loaded
  15507. * @param onError defines a callback called if there is an error
  15508. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15509. * @param invertY defines if data must be stored with Y axis inverted
  15510. * @returns the cube texture as an InternalTexture
  15511. */
  15512. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15513. var _this = this;
  15514. if (onLoad === void 0) { onLoad = null; }
  15515. if (onError === void 0) { onError = null; }
  15516. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15517. if (invertY === void 0) { invertY = false; }
  15518. var gl = this._gl;
  15519. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15520. scene._addPendingData(texture);
  15521. texture.url = url;
  15522. this._internalTexturesCache.push(texture);
  15523. var onerror = function (request, exception) {
  15524. scene._removePendingData(texture);
  15525. if (onError && request) {
  15526. onError(request.status + " " + request.statusText, exception);
  15527. }
  15528. };
  15529. var internalCallback = function (data) {
  15530. var width = texture.width;
  15531. var faceDataArrays = callback(data);
  15532. if (!faceDataArrays) {
  15533. return;
  15534. }
  15535. if (mipmapGenerator) {
  15536. var textureType = _this._getWebGLTextureType(type);
  15537. var internalFormat = _this._getInternalFormat(format);
  15538. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15539. var needConversion = false;
  15540. if (internalFormat === gl.RGB) {
  15541. internalFormat = gl.RGBA;
  15542. needConversion = true;
  15543. }
  15544. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15545. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15546. var mipData = mipmapGenerator(faceDataArrays);
  15547. for (var level = 0; level < mipData.length; level++) {
  15548. var mipSize = width >> level;
  15549. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15550. var mipFaceData = mipData[level][faceIndex];
  15551. if (needConversion) {
  15552. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15553. }
  15554. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15555. }
  15556. }
  15557. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15558. }
  15559. else {
  15560. texture.generateMipMaps = !noMipmap;
  15561. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15562. }
  15563. texture.isReady = true;
  15564. // this.resetTextureCache();
  15565. scene._removePendingData(texture);
  15566. if (onLoad) {
  15567. onLoad();
  15568. }
  15569. };
  15570. this._loadFile(url, function (data) {
  15571. internalCallback(data);
  15572. }, undefined, scene.database, true, onerror);
  15573. return texture;
  15574. };
  15575. ;
  15576. /**
  15577. * Update a raw 3D texture
  15578. * @param texture defines the texture to update
  15579. * @param data defines the data to store
  15580. * @param format defines the data format
  15581. * @param invertY defines if data must be stored with Y axis inverted
  15582. * @param compression defines the used compression (can be null)
  15583. */
  15584. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15585. if (compression === void 0) { compression = null; }
  15586. var internalFormat = this._getInternalFormat(format);
  15587. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15588. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15589. if (!this._doNotHandleContextLost) {
  15590. texture._bufferView = data;
  15591. texture.format = format;
  15592. texture.invertY = invertY;
  15593. texture._compression = compression;
  15594. }
  15595. if (texture.width % 4 !== 0) {
  15596. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15597. }
  15598. if (compression && data) {
  15599. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15600. }
  15601. else {
  15602. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15603. }
  15604. if (texture.generateMipMaps) {
  15605. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15606. }
  15607. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15608. // this.resetTextureCache();
  15609. texture.isReady = true;
  15610. };
  15611. /**
  15612. * Creates a new raw 3D texture
  15613. * @param data defines the data used to create the texture
  15614. * @param width defines the width of the texture
  15615. * @param height defines the height of the texture
  15616. * @param depth defines the depth of the texture
  15617. * @param format defines the format of the texture
  15618. * @param generateMipMaps defines if the engine must generate mip levels
  15619. * @param invertY defines if data must be stored with Y axis inverted
  15620. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15621. * @param compression defines the compressed used (can be null)
  15622. * @returns a new raw 3D texture (stored in an InternalTexture)
  15623. */
  15624. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15625. if (compression === void 0) { compression = null; }
  15626. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15627. texture.baseWidth = width;
  15628. texture.baseHeight = height;
  15629. texture.baseDepth = depth;
  15630. texture.width = width;
  15631. texture.height = height;
  15632. texture.depth = depth;
  15633. texture.format = format;
  15634. texture.generateMipMaps = generateMipMaps;
  15635. texture.samplingMode = samplingMode;
  15636. texture.is3D = true;
  15637. if (!this._doNotHandleContextLost) {
  15638. texture._bufferView = data;
  15639. }
  15640. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15641. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15642. // Filters
  15643. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15644. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15645. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15646. if (generateMipMaps) {
  15647. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15648. }
  15649. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15650. this._internalTexturesCache.push(texture);
  15651. return texture;
  15652. };
  15653. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15654. var gl = this._gl;
  15655. if (!gl) {
  15656. return;
  15657. }
  15658. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15659. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15660. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15661. if (!noMipmap && !isCompressed) {
  15662. gl.generateMipmap(gl.TEXTURE_2D);
  15663. }
  15664. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15665. // this.resetTextureCache();
  15666. if (scene) {
  15667. scene._removePendingData(texture);
  15668. }
  15669. texture.onLoadedObservable.notifyObservers(texture);
  15670. texture.onLoadedObservable.clear();
  15671. };
  15672. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15673. var _this = this;
  15674. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15675. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15676. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15677. var gl = this._gl;
  15678. if (!gl) {
  15679. return;
  15680. }
  15681. if (!texture._webGLTexture) {
  15682. // this.resetTextureCache();
  15683. if (scene) {
  15684. scene._removePendingData(texture);
  15685. }
  15686. return;
  15687. }
  15688. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15689. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15690. texture.baseWidth = width;
  15691. texture.baseHeight = height;
  15692. texture.width = potWidth;
  15693. texture.height = potHeight;
  15694. texture.isReady = true;
  15695. if (processFunction(potWidth, potHeight, function () {
  15696. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15697. })) {
  15698. // Returning as texture needs extra async steps
  15699. return;
  15700. }
  15701. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15702. };
  15703. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15704. // Create new RGBA data container.
  15705. var rgbaData;
  15706. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15707. rgbaData = new Float32Array(width * height * 4);
  15708. }
  15709. else {
  15710. rgbaData = new Uint32Array(width * height * 4);
  15711. }
  15712. // Convert each pixel.
  15713. for (var x = 0; x < width; x++) {
  15714. for (var y = 0; y < height; y++) {
  15715. var index = (y * width + x) * 3;
  15716. var newIndex = (y * width + x) * 4;
  15717. // Map Old Value to new value.
  15718. rgbaData[newIndex + 0] = rgbData[index + 0];
  15719. rgbaData[newIndex + 1] = rgbData[index + 1];
  15720. rgbaData[newIndex + 2] = rgbData[index + 2];
  15721. // Add fully opaque alpha channel.
  15722. rgbaData[newIndex + 3] = 1;
  15723. }
  15724. }
  15725. return rgbaData;
  15726. };
  15727. /** @ignore */
  15728. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15729. var gl = this._gl;
  15730. if (texture._framebuffer) {
  15731. gl.deleteFramebuffer(texture._framebuffer);
  15732. texture._framebuffer = null;
  15733. }
  15734. if (texture._depthStencilBuffer) {
  15735. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15736. texture._depthStencilBuffer = null;
  15737. }
  15738. if (texture._MSAAFramebuffer) {
  15739. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15740. texture._MSAAFramebuffer = null;
  15741. }
  15742. if (texture._MSAARenderBuffer) {
  15743. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15744. texture._MSAARenderBuffer = null;
  15745. }
  15746. };
  15747. /** @ignore */
  15748. Engine.prototype._releaseTexture = function (texture) {
  15749. var gl = this._gl;
  15750. this._releaseFramebufferObjects(texture);
  15751. gl.deleteTexture(texture._webGLTexture);
  15752. // Unbind channels
  15753. this.unbindAllTextures();
  15754. var index = this._internalTexturesCache.indexOf(texture);
  15755. if (index !== -1) {
  15756. this._internalTexturesCache.splice(index, 1);
  15757. }
  15758. // Integrated fixed lod samplers.
  15759. if (texture._lodTextureHigh) {
  15760. texture._lodTextureHigh.dispose();
  15761. }
  15762. if (texture._lodTextureMid) {
  15763. texture._lodTextureMid.dispose();
  15764. }
  15765. if (texture._lodTextureLow) {
  15766. texture._lodTextureLow.dispose();
  15767. }
  15768. // Set output texture of post process to null if the texture has been released/disposed
  15769. this.scenes.forEach(function (scene) {
  15770. scene.postProcesses.forEach(function (postProcess) {
  15771. if (postProcess._outputTexture == texture) {
  15772. postProcess._outputTexture = null;
  15773. }
  15774. });
  15775. scene.cameras.forEach(function (camera) {
  15776. camera._postProcesses.forEach(function (postProcess) {
  15777. if (postProcess) {
  15778. if (postProcess._outputTexture == texture) {
  15779. postProcess._outputTexture = null;
  15780. }
  15781. }
  15782. });
  15783. });
  15784. });
  15785. };
  15786. Engine.prototype.setProgram = function (program) {
  15787. if (this._currentProgram !== program) {
  15788. this._gl.useProgram(program);
  15789. this._currentProgram = program;
  15790. }
  15791. };
  15792. /**
  15793. * Binds an effect to the webGL context
  15794. * @param effect defines the effect to bind
  15795. */
  15796. Engine.prototype.bindSamplers = function (effect) {
  15797. this.setProgram(effect.getProgram());
  15798. var samplers = effect.getSamplers();
  15799. for (var index = 0; index < samplers.length; index++) {
  15800. var uniform = effect.getUniform(samplers[index]);
  15801. if (uniform) {
  15802. this._boundUniforms[index] = uniform;
  15803. }
  15804. }
  15805. this._currentEffect = null;
  15806. };
  15807. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  15808. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  15809. return;
  15810. }
  15811. // Remove
  15812. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15813. // Bind last to it
  15814. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  15815. // Bind to dummy
  15816. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  15817. };
  15818. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  15819. if (!internalTexture) {
  15820. return -1;
  15821. }
  15822. internalTexture._initialSlot = channel;
  15823. if (this.disableTextureBindingOptimization) {
  15824. if (channel !== internalTexture._designatedSlot) {
  15825. this._textureCollisions.addCount(1, false);
  15826. }
  15827. }
  15828. else {
  15829. if (channel !== internalTexture._designatedSlot) {
  15830. if (internalTexture._designatedSlot > -1) {
  15831. return internalTexture._designatedSlot;
  15832. }
  15833. else {
  15834. // No slot for this texture, let's pick a new one (if we find a free slot)
  15835. if (this._nextFreeTextureSlots.length) {
  15836. return this._nextFreeTextureSlots[0];
  15837. }
  15838. // We need to recycle the oldest bound texture, sorry.
  15839. this._textureCollisions.addCount(1, false);
  15840. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  15841. }
  15842. }
  15843. }
  15844. return channel;
  15845. };
  15846. Engine.prototype._linkTrackers = function (previous, next) {
  15847. previous.next = next;
  15848. next.previous = previous;
  15849. };
  15850. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  15851. var currentSlot = internalTexture._designatedSlot;
  15852. if (currentSlot === -1) {
  15853. return -1;
  15854. }
  15855. internalTexture._designatedSlot = -1;
  15856. if (this.disableTextureBindingOptimization) {
  15857. return -1;
  15858. }
  15859. // Remove from bound list
  15860. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15861. // Free the slot
  15862. this._boundTexturesCache[currentSlot] = null;
  15863. this._nextFreeTextureSlots.push(currentSlot);
  15864. return currentSlot;
  15865. };
  15866. Engine.prototype._activateCurrentTexture = function () {
  15867. if (this._currentTextureChannel !== this._activeChannel) {
  15868. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  15869. this._currentTextureChannel = this._activeChannel;
  15870. }
  15871. };
  15872. /** @ignore */
  15873. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  15874. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  15875. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  15876. this._activeChannel = texture._designatedSlot;
  15877. }
  15878. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  15879. var isTextureForRendering = texture && texture._initialSlot > -1;
  15880. if (currentTextureBound !== texture) {
  15881. if (currentTextureBound) {
  15882. this._removeDesignatedSlot(currentTextureBound);
  15883. }
  15884. this._activateCurrentTexture();
  15885. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  15886. this._boundTexturesCache[this._activeChannel] = texture;
  15887. if (texture) {
  15888. if (!this.disableTextureBindingOptimization) {
  15889. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  15890. if (slotIndex > -1) {
  15891. this._nextFreeTextureSlots.splice(slotIndex, 1);
  15892. }
  15893. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  15894. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  15895. }
  15896. texture._designatedSlot = this._activeChannel;
  15897. }
  15898. }
  15899. else if (forTextureDataUpdate) {
  15900. this._activateCurrentTexture();
  15901. }
  15902. if (isTextureForRendering && !forTextureDataUpdate) {
  15903. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  15904. }
  15905. };
  15906. /** @ignore */
  15907. Engine.prototype._bindTexture = function (channel, texture) {
  15908. if (channel < 0) {
  15909. return;
  15910. }
  15911. if (texture) {
  15912. channel = this._getCorrectTextureChannel(channel, texture);
  15913. }
  15914. this._activeChannel = channel;
  15915. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  15916. };
  15917. /**
  15918. * Sets a texture to the webGL context from a postprocess
  15919. * @param channel defines the channel to use
  15920. * @param postProcess defines the source postprocess
  15921. */
  15922. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  15923. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  15924. };
  15925. /**
  15926. * Binds the output of the passed in post process to the texture channel specified
  15927. * @param channel The channel the texture should be bound to
  15928. * @param postProcess The post process which's output should be bound
  15929. */
  15930. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  15931. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  15932. };
  15933. /**
  15934. * Unbind all textures from the webGL context
  15935. */
  15936. Engine.prototype.unbindAllTextures = function () {
  15937. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  15938. this._activeChannel = channel;
  15939. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15940. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15941. if (this.webGLVersion > 1) {
  15942. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15943. }
  15944. }
  15945. };
  15946. /**
  15947. * Sets a texture to the according uniform.
  15948. * @param channel The texture channel
  15949. * @param uniform The uniform to set
  15950. * @param texture The texture to apply
  15951. */
  15952. Engine.prototype.setTexture = function (channel, uniform, texture) {
  15953. if (channel < 0) {
  15954. return;
  15955. }
  15956. if (uniform) {
  15957. this._boundUniforms[channel] = uniform;
  15958. }
  15959. this._setTexture(channel, texture);
  15960. };
  15961. /**
  15962. * Sets a depth stencil texture from a render target to the according uniform.
  15963. * @param channel The texture channel
  15964. * @param uniform The uniform to set
  15965. * @param texture The render target texture containing the depth stencil texture to apply
  15966. */
  15967. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  15968. if (channel < 0) {
  15969. return;
  15970. }
  15971. if (uniform) {
  15972. this._boundUniforms[channel] = uniform;
  15973. }
  15974. if (!texture || !texture.depthStencilTexture) {
  15975. this._setTexture(channel, null);
  15976. }
  15977. else {
  15978. this._setTexture(channel, texture, false, true);
  15979. }
  15980. };
  15981. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  15982. var uniform = this._boundUniforms[sourceSlot];
  15983. if (uniform._currentState === destination) {
  15984. return;
  15985. }
  15986. this._gl.uniform1i(uniform, destination);
  15987. uniform._currentState = destination;
  15988. };
  15989. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  15990. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  15991. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  15992. // Not ready?
  15993. if (!texture) {
  15994. if (this._boundTexturesCache[channel] != null) {
  15995. this._activeChannel = channel;
  15996. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15997. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15998. if (this.webGLVersion > 1) {
  15999. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16000. }
  16001. }
  16002. return false;
  16003. }
  16004. // Video
  16005. if (texture.video) {
  16006. this._activeChannel = channel;
  16007. texture.update();
  16008. }
  16009. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  16010. texture.delayLoad();
  16011. return false;
  16012. }
  16013. var internalTexture;
  16014. if (depthStencilTexture) {
  16015. internalTexture = texture.depthStencilTexture;
  16016. }
  16017. else if (texture.isReady()) {
  16018. internalTexture = texture.getInternalTexture();
  16019. }
  16020. else if (texture.isCube) {
  16021. internalTexture = this.emptyCubeTexture;
  16022. }
  16023. else if (texture.is3D) {
  16024. internalTexture = this.emptyTexture3D;
  16025. }
  16026. else {
  16027. internalTexture = this.emptyTexture;
  16028. }
  16029. if (!isPartOfTextureArray) {
  16030. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16031. }
  16032. if (this._boundTexturesCache[channel] === internalTexture) {
  16033. this._moveBoundTextureOnTop(internalTexture);
  16034. if (!isPartOfTextureArray) {
  16035. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16036. }
  16037. return false;
  16038. }
  16039. this._activeChannel = channel;
  16040. if (internalTexture && internalTexture.is3D) {
  16041. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16042. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16043. internalTexture._cachedWrapU = texture.wrapU;
  16044. switch (texture.wrapU) {
  16045. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16046. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  16047. break;
  16048. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16049. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  16050. break;
  16051. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16052. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  16053. break;
  16054. }
  16055. }
  16056. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16057. internalTexture._cachedWrapV = texture.wrapV;
  16058. switch (texture.wrapV) {
  16059. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16060. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  16061. break;
  16062. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16063. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  16064. break;
  16065. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16066. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  16067. break;
  16068. }
  16069. }
  16070. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16071. internalTexture._cachedWrapR = texture.wrapR;
  16072. switch (texture.wrapR) {
  16073. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16074. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  16075. break;
  16076. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16077. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  16078. break;
  16079. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16080. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  16081. break;
  16082. }
  16083. }
  16084. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16085. }
  16086. else if (internalTexture && internalTexture.isCube) {
  16087. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16088. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16089. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16090. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16091. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16092. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  16093. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16094. }
  16095. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16096. }
  16097. else {
  16098. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16099. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16100. internalTexture._cachedWrapU = texture.wrapU;
  16101. switch (texture.wrapU) {
  16102. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16103. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  16104. break;
  16105. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16106. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  16107. break;
  16108. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16109. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  16110. break;
  16111. }
  16112. }
  16113. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16114. internalTexture._cachedWrapV = texture.wrapV;
  16115. switch (texture.wrapV) {
  16116. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16117. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  16118. break;
  16119. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16120. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  16121. break;
  16122. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16123. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  16124. break;
  16125. }
  16126. }
  16127. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16128. }
  16129. return true;
  16130. };
  16131. /**
  16132. * Sets an array of texture to the webGL context
  16133. * @param channel defines the channel where the texture array must be set
  16134. * @param uniform defines the associated uniform location
  16135. * @param textures defines the array of textures to bind
  16136. */
  16137. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16138. if (channel < 0 || !uniform) {
  16139. return;
  16140. }
  16141. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16142. this._textureUnits = new Int32Array(textures.length);
  16143. }
  16144. for (var i = 0; i < textures.length; i++) {
  16145. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16146. }
  16147. this._gl.uniform1iv(uniform, this._textureUnits);
  16148. for (var index = 0; index < textures.length; index++) {
  16149. this._setTexture(this._textureUnits[index], textures[index], true);
  16150. }
  16151. };
  16152. /** @ignore */
  16153. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  16154. var internalTexture = texture.getInternalTexture();
  16155. if (!internalTexture) {
  16156. return;
  16157. }
  16158. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16159. var value = texture.anisotropicFilteringLevel;
  16160. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16161. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16162. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16163. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16164. }
  16165. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16166. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  16167. internalTexture._cachedAnisotropicFilteringLevel = value;
  16168. }
  16169. };
  16170. /**
  16171. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16172. * @param x defines the x coordinate of the rectangle where pixels must be read
  16173. * @param y defines the y coordinate of the rectangle where pixels must be read
  16174. * @param width defines the width of the rectangle where pixels must be read
  16175. * @param height defines the height of the rectangle where pixels must be read
  16176. * @returns a Uint8Array containing RGBA colors
  16177. */
  16178. Engine.prototype.readPixels = function (x, y, width, height) {
  16179. var data = new Uint8Array(height * width * 4);
  16180. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16181. return data;
  16182. };
  16183. /**
  16184. * Add an externaly attached data from its key.
  16185. * This method call will fail and return false, if such key already exists.
  16186. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16187. * @param key the unique key that identifies the data
  16188. * @param data the data object to associate to the key for this Engine instance
  16189. * @return true if no such key were already present and the data was added successfully, false otherwise
  16190. */
  16191. Engine.prototype.addExternalData = function (key, data) {
  16192. if (!this._externalData) {
  16193. this._externalData = new BABYLON.StringDictionary();
  16194. }
  16195. return this._externalData.add(key, data);
  16196. };
  16197. /**
  16198. * Get an externaly attached data from its key
  16199. * @param key the unique key that identifies the data
  16200. * @return the associated data, if present (can be null), or undefined if not present
  16201. */
  16202. Engine.prototype.getExternalData = function (key) {
  16203. if (!this._externalData) {
  16204. this._externalData = new BABYLON.StringDictionary();
  16205. }
  16206. return this._externalData.get(key);
  16207. };
  16208. /**
  16209. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16210. * @param key the unique key that identifies the data
  16211. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16212. * @return the associated data, can be null if the factory returned null.
  16213. */
  16214. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16215. if (!this._externalData) {
  16216. this._externalData = new BABYLON.StringDictionary();
  16217. }
  16218. return this._externalData.getOrAddWithFactory(key, factory);
  16219. };
  16220. /**
  16221. * Remove an externaly attached data from the Engine instance
  16222. * @param key the unique key that identifies the data
  16223. * @return true if the data was successfully removed, false if it doesn't exist
  16224. */
  16225. Engine.prototype.removeExternalData = function (key) {
  16226. if (!this._externalData) {
  16227. this._externalData = new BABYLON.StringDictionary();
  16228. }
  16229. return this._externalData.remove(key);
  16230. };
  16231. /**
  16232. * Unbind all vertex attributes from the webGL context
  16233. */
  16234. Engine.prototype.unbindAllAttributes = function () {
  16235. if (this._mustWipeVertexAttributes) {
  16236. this._mustWipeVertexAttributes = false;
  16237. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16238. this._gl.disableVertexAttribArray(i);
  16239. this._vertexAttribArraysEnabled[i] = false;
  16240. this._currentBufferPointers[i].active = false;
  16241. }
  16242. return;
  16243. }
  16244. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16245. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16246. continue;
  16247. }
  16248. this._gl.disableVertexAttribArray(i);
  16249. this._vertexAttribArraysEnabled[i] = false;
  16250. this._currentBufferPointers[i].active = false;
  16251. }
  16252. };
  16253. /**
  16254. * 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
  16255. */
  16256. Engine.prototype.releaseEffects = function () {
  16257. for (var name in this._compiledEffects) {
  16258. this._deleteProgram(this._compiledEffects[name]._program);
  16259. }
  16260. this._compiledEffects = {};
  16261. };
  16262. /**
  16263. * Dispose and release all associated resources
  16264. */
  16265. Engine.prototype.dispose = function () {
  16266. this.hideLoadingUI();
  16267. this.stopRenderLoop();
  16268. // Release postProcesses
  16269. while (this.postProcesses.length) {
  16270. this.postProcesses[0].dispose();
  16271. }
  16272. // Empty texture
  16273. if (this._emptyTexture) {
  16274. this._releaseTexture(this._emptyTexture);
  16275. this._emptyTexture = null;
  16276. }
  16277. if (this._emptyCubeTexture) {
  16278. this._releaseTexture(this._emptyCubeTexture);
  16279. this._emptyCubeTexture = null;
  16280. }
  16281. // Rescale PP
  16282. if (this._rescalePostProcess) {
  16283. this._rescalePostProcess.dispose();
  16284. }
  16285. // Release scenes
  16286. while (this.scenes.length) {
  16287. this.scenes[0].dispose();
  16288. }
  16289. // Release audio engine
  16290. if (Engine.audioEngine) {
  16291. Engine.audioEngine.dispose();
  16292. }
  16293. // Release effects
  16294. this.releaseEffects();
  16295. // Unbind
  16296. this.unbindAllAttributes();
  16297. this._boundUniforms = [];
  16298. if (this._dummyFramebuffer) {
  16299. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16300. }
  16301. //WebVR
  16302. this.disableVR();
  16303. // Events
  16304. if (BABYLON.Tools.IsWindowObjectExist()) {
  16305. window.removeEventListener("blur", this._onBlur);
  16306. window.removeEventListener("focus", this._onFocus);
  16307. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16308. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16309. if (this._renderingCanvas) {
  16310. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16311. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16312. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16313. if (!this._doNotHandleContextLost) {
  16314. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16315. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16316. }
  16317. }
  16318. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16319. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16320. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16321. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16322. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16323. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16324. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16325. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16326. if (this._onVrDisplayConnect) {
  16327. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16328. if (this._onVrDisplayDisconnect) {
  16329. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16330. }
  16331. if (this._onVrDisplayPresentChange) {
  16332. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16333. }
  16334. this._onVrDisplayConnect = null;
  16335. this._onVrDisplayDisconnect = null;
  16336. }
  16337. }
  16338. // Remove from Instances
  16339. var index = Engine.Instances.indexOf(this);
  16340. if (index >= 0) {
  16341. Engine.Instances.splice(index, 1);
  16342. }
  16343. this._workingCanvas = null;
  16344. this._workingContext = null;
  16345. this._currentBufferPointers = [];
  16346. this._renderingCanvas = null;
  16347. this._currentProgram = null;
  16348. this._bindedRenderFunction = null;
  16349. this.onResizeObservable.clear();
  16350. this.onCanvasBlurObservable.clear();
  16351. this.onCanvasFocusObservable.clear();
  16352. this.onCanvasPointerOutObservable.clear();
  16353. this.onBeginFrameObservable.clear();
  16354. this.onEndFrameObservable.clear();
  16355. BABYLON.Effect.ResetCache();
  16356. // Abort active requests
  16357. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16358. var request = _a[_i];
  16359. request.abort();
  16360. }
  16361. };
  16362. // Loading screen
  16363. /**
  16364. * Display the loading screen
  16365. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16366. */
  16367. Engine.prototype.displayLoadingUI = function () {
  16368. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16369. return;
  16370. }
  16371. var loadingScreen = this.loadingScreen;
  16372. if (loadingScreen) {
  16373. loadingScreen.displayLoadingUI();
  16374. }
  16375. };
  16376. /**
  16377. * Hide the loading screen
  16378. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16379. */
  16380. Engine.prototype.hideLoadingUI = function () {
  16381. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16382. return;
  16383. }
  16384. var loadingScreen = this.loadingScreen;
  16385. if (loadingScreen) {
  16386. loadingScreen.hideLoadingUI();
  16387. }
  16388. };
  16389. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16390. /**
  16391. * Gets the current loading screen object
  16392. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16393. */
  16394. get: function () {
  16395. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16396. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16397. return this._loadingScreen;
  16398. },
  16399. /**
  16400. * Sets the current loading screen object
  16401. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16402. */
  16403. set: function (loadingScreen) {
  16404. this._loadingScreen = loadingScreen;
  16405. },
  16406. enumerable: true,
  16407. configurable: true
  16408. });
  16409. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16410. /**
  16411. * Sets the current loading screen text
  16412. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16413. */
  16414. set: function (text) {
  16415. this.loadingScreen.loadingUIText = text;
  16416. },
  16417. enumerable: true,
  16418. configurable: true
  16419. });
  16420. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16421. /**
  16422. * Sets the current loading screen background color
  16423. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16424. */
  16425. set: function (color) {
  16426. this.loadingScreen.loadingUIBackgroundColor = color;
  16427. },
  16428. enumerable: true,
  16429. configurable: true
  16430. });
  16431. /**
  16432. * Attach a new callback raised when context lost event is fired
  16433. * @param callback defines the callback to call
  16434. */
  16435. Engine.prototype.attachContextLostEvent = function (callback) {
  16436. if (this._renderingCanvas) {
  16437. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16438. }
  16439. };
  16440. /**
  16441. * Attach a new callback raised when context restored event is fired
  16442. * @param callback defines the callback to call
  16443. */
  16444. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16445. if (this._renderingCanvas) {
  16446. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16447. }
  16448. };
  16449. /**
  16450. * Gets the source code of the vertex shader associated with a specific webGL program
  16451. * @param program defines the program to use
  16452. * @returns a string containing the source code of the vertex shader associated with the program
  16453. */
  16454. Engine.prototype.getVertexShaderSource = function (program) {
  16455. var shaders = this._gl.getAttachedShaders(program);
  16456. if (!shaders) {
  16457. return null;
  16458. }
  16459. return this._gl.getShaderSource(shaders[0]);
  16460. };
  16461. /**
  16462. * Gets the source code of the fragment shader associated with a specific webGL program
  16463. * @param program defines the program to use
  16464. * @returns a string containing the source code of the fragment shader associated with the program
  16465. */
  16466. Engine.prototype.getFragmentShaderSource = function (program) {
  16467. var shaders = this._gl.getAttachedShaders(program);
  16468. if (!shaders) {
  16469. return null;
  16470. }
  16471. return this._gl.getShaderSource(shaders[1]);
  16472. };
  16473. /**
  16474. * Get the current error code of the webGL context
  16475. * @returns the error code
  16476. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16477. */
  16478. Engine.prototype.getError = function () {
  16479. return this._gl.getError();
  16480. };
  16481. // FPS
  16482. /**
  16483. * Gets the current framerate
  16484. * @returns a number representing the framerate
  16485. */
  16486. Engine.prototype.getFps = function () {
  16487. return this._fps;
  16488. };
  16489. /**
  16490. * Gets the time spent between current and previous frame
  16491. * @returns a number representing the delta time in ms
  16492. */
  16493. Engine.prototype.getDeltaTime = function () {
  16494. return this._deltaTime;
  16495. };
  16496. Engine.prototype._measureFps = function () {
  16497. this._performanceMonitor.sampleFrame();
  16498. this._fps = this._performanceMonitor.averageFPS;
  16499. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16500. };
  16501. /** @ignore */
  16502. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16503. if (faceIndex === void 0) { faceIndex = -1; }
  16504. var gl = this._gl;
  16505. if (!this._dummyFramebuffer) {
  16506. var dummy = gl.createFramebuffer();
  16507. if (!dummy) {
  16508. throw new Error("Unable to create dummy framebuffer");
  16509. }
  16510. this._dummyFramebuffer = dummy;
  16511. }
  16512. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16513. if (faceIndex > -1) {
  16514. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16515. }
  16516. else {
  16517. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16518. }
  16519. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16520. var buffer;
  16521. switch (readType) {
  16522. case gl.UNSIGNED_BYTE:
  16523. buffer = new Uint8Array(4 * width * height);
  16524. readType = gl.UNSIGNED_BYTE;
  16525. break;
  16526. default:
  16527. buffer = new Float32Array(4 * width * height);
  16528. readType = gl.FLOAT;
  16529. break;
  16530. }
  16531. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16532. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16533. return buffer;
  16534. };
  16535. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16536. if (this._webGLVersion > 1) {
  16537. return this._caps.colorBufferFloat;
  16538. }
  16539. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16540. };
  16541. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16542. if (this._webGLVersion > 1) {
  16543. return this._caps.colorBufferFloat;
  16544. }
  16545. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16546. };
  16547. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16548. Engine.prototype._canRenderToFramebuffer = function (type) {
  16549. var gl = this._gl;
  16550. //clear existing errors
  16551. while (gl.getError() !== gl.NO_ERROR) { }
  16552. var successful = true;
  16553. var texture = gl.createTexture();
  16554. gl.bindTexture(gl.TEXTURE_2D, texture);
  16555. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16556. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16557. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16558. var fb = gl.createFramebuffer();
  16559. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16560. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16561. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16562. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16563. successful = successful && (gl.getError() === gl.NO_ERROR);
  16564. //try render by clearing frame buffer's color buffer
  16565. if (successful) {
  16566. gl.clear(gl.COLOR_BUFFER_BIT);
  16567. successful = successful && (gl.getError() === gl.NO_ERROR);
  16568. }
  16569. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16570. if (successful) {
  16571. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16572. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16573. var readFormat = gl.RGBA;
  16574. var readType = gl.UNSIGNED_BYTE;
  16575. var buffer = new Uint8Array(4);
  16576. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16577. successful = successful && (gl.getError() === gl.NO_ERROR);
  16578. }
  16579. //clean up
  16580. gl.deleteTexture(texture);
  16581. gl.deleteFramebuffer(fb);
  16582. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16583. //clear accumulated errors
  16584. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16585. return successful;
  16586. };
  16587. /** @ignore */
  16588. Engine.prototype._getWebGLTextureType = function (type) {
  16589. if (type === Engine.TEXTURETYPE_FLOAT) {
  16590. return this._gl.FLOAT;
  16591. }
  16592. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16593. // Add Half Float Constant.
  16594. return this._gl.HALF_FLOAT_OES;
  16595. }
  16596. return this._gl.UNSIGNED_BYTE;
  16597. };
  16598. ;
  16599. Engine.prototype._getInternalFormat = function (format) {
  16600. var internalFormat = this._gl.RGBA;
  16601. switch (format) {
  16602. case Engine.TEXTUREFORMAT_ALPHA:
  16603. internalFormat = this._gl.ALPHA;
  16604. break;
  16605. case Engine.TEXTUREFORMAT_LUMINANCE:
  16606. internalFormat = this._gl.LUMINANCE;
  16607. break;
  16608. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16609. internalFormat = this._gl.LUMINANCE_ALPHA;
  16610. break;
  16611. case Engine.TEXTUREFORMAT_RGB:
  16612. case Engine.TEXTUREFORMAT_RGB32F:
  16613. internalFormat = this._gl.RGB;
  16614. break;
  16615. case Engine.TEXTUREFORMAT_RGBA:
  16616. case Engine.TEXTUREFORMAT_RGBA32F:
  16617. internalFormat = this._gl.RGBA;
  16618. break;
  16619. case Engine.TEXTUREFORMAT_R32F:
  16620. internalFormat = this._gl.RED;
  16621. break;
  16622. case Engine.TEXTUREFORMAT_RG32F:
  16623. internalFormat = this._gl.RG;
  16624. break;
  16625. }
  16626. return internalFormat;
  16627. };
  16628. /** @ignore */
  16629. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16630. if (this._webGLVersion === 1) {
  16631. if (format) {
  16632. switch (format) {
  16633. case Engine.TEXTUREFORMAT_LUMINANCE:
  16634. return this._gl.LUMINANCE;
  16635. }
  16636. }
  16637. return this._gl.RGBA;
  16638. }
  16639. if (type === Engine.TEXTURETYPE_FLOAT) {
  16640. if (format) {
  16641. switch (format) {
  16642. case Engine.TEXTUREFORMAT_R32F:
  16643. return this._gl.R32F;
  16644. case Engine.TEXTUREFORMAT_RG32F:
  16645. return this._gl.RG32F;
  16646. case Engine.TEXTUREFORMAT_RGB32F:
  16647. return this._gl.RGB32F;
  16648. }
  16649. }
  16650. return this._gl.RGBA32F;
  16651. }
  16652. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16653. return this._gl.RGBA16F;
  16654. }
  16655. if (format) {
  16656. switch (format) {
  16657. case Engine.TEXTUREFORMAT_LUMINANCE:
  16658. return this._gl.LUMINANCE;
  16659. }
  16660. }
  16661. return this._gl.RGBA;
  16662. };
  16663. ;
  16664. /** @ignore */
  16665. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16666. if (type === Engine.TEXTURETYPE_FLOAT) {
  16667. return this._gl.RGBA32F;
  16668. }
  16669. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16670. return this._gl.RGBA16F;
  16671. }
  16672. return this._gl.RGBA8;
  16673. };
  16674. ;
  16675. /**
  16676. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16677. * @return the new query
  16678. */
  16679. Engine.prototype.createQuery = function () {
  16680. return this._gl.createQuery();
  16681. };
  16682. /**
  16683. * Delete and release a webGL query
  16684. * @param query defines the query to delete
  16685. * @return the current engine
  16686. */
  16687. Engine.prototype.deleteQuery = function (query) {
  16688. this._gl.deleteQuery(query);
  16689. return this;
  16690. };
  16691. /**
  16692. * Check if a given query has resolved and got its value
  16693. * @param query defines the query to check
  16694. * @returns true if the query got its value
  16695. */
  16696. Engine.prototype.isQueryResultAvailable = function (query) {
  16697. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16698. };
  16699. /**
  16700. * Gets the value of a given query
  16701. * @param query defines the query to check
  16702. * @returns the value of the query
  16703. */
  16704. Engine.prototype.getQueryResult = function (query) {
  16705. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16706. };
  16707. /**
  16708. * Initiates an occlusion query
  16709. * @param algorithmType defines the algorithm to use
  16710. * @param query defines the query to use
  16711. * @returns the current engine
  16712. * @see http://doc.babylonjs.com/features/occlusionquery
  16713. */
  16714. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16715. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16716. this._gl.beginQuery(glAlgorithm, query);
  16717. return this;
  16718. };
  16719. /**
  16720. * Ends an occlusion query
  16721. * @see http://doc.babylonjs.com/features/occlusionquery
  16722. * @param algorithmType defines the algorithm to use
  16723. * @returns the current engine
  16724. */
  16725. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16726. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16727. this._gl.endQuery(glAlgorithm);
  16728. return this;
  16729. };
  16730. /* Time queries */
  16731. Engine.prototype._createTimeQuery = function () {
  16732. var timerQuery = this._caps.timerQuery;
  16733. if (timerQuery.createQueryEXT) {
  16734. return timerQuery.createQueryEXT();
  16735. }
  16736. return this.createQuery();
  16737. };
  16738. Engine.prototype._deleteTimeQuery = function (query) {
  16739. var timerQuery = this._caps.timerQuery;
  16740. if (timerQuery.deleteQueryEXT) {
  16741. timerQuery.deleteQueryEXT(query);
  16742. return;
  16743. }
  16744. this.deleteQuery(query);
  16745. };
  16746. Engine.prototype._getTimeQueryResult = function (query) {
  16747. var timerQuery = this._caps.timerQuery;
  16748. if (timerQuery.getQueryObjectEXT) {
  16749. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16750. }
  16751. return this.getQueryResult(query);
  16752. };
  16753. Engine.prototype._getTimeQueryAvailability = function (query) {
  16754. var timerQuery = this._caps.timerQuery;
  16755. if (timerQuery.getQueryObjectEXT) {
  16756. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16757. }
  16758. return this.isQueryResultAvailable(query);
  16759. };
  16760. /**
  16761. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16762. * Please note that only one query can be issued at a time
  16763. * @returns a time token used to track the time span
  16764. */
  16765. Engine.prototype.startTimeQuery = function () {
  16766. var timerQuery = this._caps.timerQuery;
  16767. if (!timerQuery) {
  16768. return null;
  16769. }
  16770. var token = new BABYLON._TimeToken();
  16771. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16772. if (this._caps.canUseTimestampForTimerQuery) {
  16773. token._startTimeQuery = this._createTimeQuery();
  16774. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16775. }
  16776. else {
  16777. if (this._currentNonTimestampToken) {
  16778. return this._currentNonTimestampToken;
  16779. }
  16780. token._timeElapsedQuery = this._createTimeQuery();
  16781. if (timerQuery.beginQueryEXT) {
  16782. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16783. }
  16784. else {
  16785. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16786. }
  16787. this._currentNonTimestampToken = token;
  16788. }
  16789. return token;
  16790. };
  16791. /**
  16792. * Ends a time query
  16793. * @param token defines the token used to measure the time span
  16794. * @returns the time spent (in ns)
  16795. */
  16796. Engine.prototype.endTimeQuery = function (token) {
  16797. var timerQuery = this._caps.timerQuery;
  16798. if (!timerQuery || !token) {
  16799. return -1;
  16800. }
  16801. if (this._caps.canUseTimestampForTimerQuery) {
  16802. if (!token._startTimeQuery) {
  16803. return -1;
  16804. }
  16805. if (!token._endTimeQuery) {
  16806. token._endTimeQuery = this._createTimeQuery();
  16807. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  16808. }
  16809. }
  16810. else if (!token._timeElapsedQueryEnded) {
  16811. if (!token._timeElapsedQuery) {
  16812. return -1;
  16813. }
  16814. if (timerQuery.endQueryEXT) {
  16815. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  16816. }
  16817. else {
  16818. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  16819. }
  16820. token._timeElapsedQueryEnded = true;
  16821. }
  16822. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16823. var available = false;
  16824. if (token._endTimeQuery) {
  16825. available = this._getTimeQueryAvailability(token._endTimeQuery);
  16826. }
  16827. else if (token._timeElapsedQuery) {
  16828. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  16829. }
  16830. if (available && !disjoint) {
  16831. var result = 0;
  16832. if (this._caps.canUseTimestampForTimerQuery) {
  16833. if (!token._startTimeQuery || !token._endTimeQuery) {
  16834. return -1;
  16835. }
  16836. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  16837. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  16838. result = timeEnd - timeStart;
  16839. this._deleteTimeQuery(token._startTimeQuery);
  16840. this._deleteTimeQuery(token._endTimeQuery);
  16841. token._startTimeQuery = null;
  16842. token._endTimeQuery = null;
  16843. }
  16844. else {
  16845. if (!token._timeElapsedQuery) {
  16846. return -1;
  16847. }
  16848. result = this._getTimeQueryResult(token._timeElapsedQuery);
  16849. this._deleteTimeQuery(token._timeElapsedQuery);
  16850. token._timeElapsedQuery = null;
  16851. token._timeElapsedQueryEnded = false;
  16852. this._currentNonTimestampToken = null;
  16853. }
  16854. return result;
  16855. }
  16856. return -1;
  16857. };
  16858. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  16859. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  16860. };
  16861. // Transform feedback
  16862. /**
  16863. * Creates a webGL transform feedback object
  16864. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  16865. * @returns the webGL transform feedback object
  16866. */
  16867. Engine.prototype.createTransformFeedback = function () {
  16868. return this._gl.createTransformFeedback();
  16869. };
  16870. /**
  16871. * Delete a webGL transform feedback object
  16872. * @param value defines the webGL transform feedback object to delete
  16873. */
  16874. Engine.prototype.deleteTransformFeedback = function (value) {
  16875. this._gl.deleteTransformFeedback(value);
  16876. };
  16877. /**
  16878. * Bind a webGL transform feedback object to the webgl context
  16879. * @param value defines the webGL transform feedback object to bind
  16880. */
  16881. Engine.prototype.bindTransformFeedback = function (value) {
  16882. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  16883. };
  16884. /**
  16885. * Begins a transform feedback operation
  16886. * @param usePoints defines if points or triangles must be used
  16887. */
  16888. Engine.prototype.beginTransformFeedback = function (usePoints) {
  16889. if (usePoints === void 0) { usePoints = true; }
  16890. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  16891. };
  16892. /**
  16893. * Ends a transform feedback operation
  16894. */
  16895. Engine.prototype.endTransformFeedback = function () {
  16896. this._gl.endTransformFeedback();
  16897. };
  16898. /**
  16899. * Specify the varyings to use with transform feedback
  16900. * @param program defines the associated webGL program
  16901. * @param value defines the list of strings representing the varying names
  16902. */
  16903. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  16904. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  16905. };
  16906. /**
  16907. * Bind a webGL buffer for a transform feedback operation
  16908. * @param value defines the webGL buffer to bind
  16909. */
  16910. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  16911. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  16912. };
  16913. /** @ignore */
  16914. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  16915. var _this = this;
  16916. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  16917. this._activeRequests.push(request);
  16918. request.onCompleteObservable.add(function (request) {
  16919. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  16920. });
  16921. return request;
  16922. };
  16923. /** @ignore */
  16924. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  16925. var _this = this;
  16926. return new Promise(function (resolve, reject) {
  16927. _this._loadFile(url, function (data) {
  16928. resolve(data);
  16929. }, undefined, database, useArrayBuffer, function (request, exception) {
  16930. reject(exception);
  16931. });
  16932. });
  16933. };
  16934. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  16935. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  16936. var onload = function (data) {
  16937. loadedFiles[index] = data;
  16938. loadedFiles._internalCount++;
  16939. if (loadedFiles._internalCount === 6) {
  16940. onfinish(loadedFiles);
  16941. }
  16942. };
  16943. var onerror = function (request, exception) {
  16944. if (onErrorCallBack && request) {
  16945. onErrorCallBack(request.status + " " + request.statusText, exception);
  16946. }
  16947. };
  16948. this._loadFile(url, onload, undefined, undefined, true, onerror);
  16949. };
  16950. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  16951. if (onError === void 0) { onError = null; }
  16952. var loadedFiles = [];
  16953. loadedFiles._internalCount = 0;
  16954. for (var index = 0; index < 6; index++) {
  16955. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  16956. }
  16957. };
  16958. // Statics
  16959. /**
  16960. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  16961. * @returns true if the engine can be created
  16962. * @ignoreNaming
  16963. */
  16964. Engine.isSupported = function () {
  16965. try {
  16966. var tempcanvas = document.createElement("canvas");
  16967. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  16968. return gl != null && !!window.WebGLRenderingContext;
  16969. }
  16970. catch (e) {
  16971. return false;
  16972. }
  16973. };
  16974. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  16975. Engine.ExceptionList = [
  16976. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  16977. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16978. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16979. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16980. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16981. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  16982. ];
  16983. /** Gets the list of created engines */
  16984. Engine.Instances = new Array();
  16985. // Const statics
  16986. Engine._ALPHA_DISABLE = 0;
  16987. Engine._ALPHA_ADD = 1;
  16988. Engine._ALPHA_COMBINE = 2;
  16989. Engine._ALPHA_SUBTRACT = 3;
  16990. Engine._ALPHA_MULTIPLY = 4;
  16991. Engine._ALPHA_MAXIMIZED = 5;
  16992. Engine._ALPHA_ONEONE = 6;
  16993. Engine._ALPHA_PREMULTIPLIED = 7;
  16994. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  16995. Engine._ALPHA_INTERPOLATE = 9;
  16996. Engine._ALPHA_SCREENMODE = 10;
  16997. Engine._DELAYLOADSTATE_NONE = 0;
  16998. Engine._DELAYLOADSTATE_LOADED = 1;
  16999. Engine._DELAYLOADSTATE_LOADING = 2;
  17000. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17001. Engine._TEXTUREFORMAT_ALPHA = 0;
  17002. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17003. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17004. Engine._TEXTUREFORMAT_RGB = 4;
  17005. Engine._TEXTUREFORMAT_RGBA = 5;
  17006. Engine._TEXTUREFORMAT_R32F = 6;
  17007. Engine._TEXTUREFORMAT_RG32F = 7;
  17008. Engine._TEXTUREFORMAT_RGB32F = 8;
  17009. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17010. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17011. Engine._TEXTURETYPE_FLOAT = 1;
  17012. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17013. // Depht or Stencil test Constants.
  17014. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17015. Engine._ALWAYS = 0x0207; // 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.
  17016. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17017. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17018. Engine._LEQUAL = 0x0203; // 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.
  17019. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17020. Engine._GEQUAL = 0x0206; // 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.
  17021. Engine._NOTEQUAL = 0x0205; // 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.
  17022. // Stencil Actions Constants.
  17023. Engine._KEEP = 0x1E00;
  17024. Engine._REPLACE = 0x1E01;
  17025. Engine._INCR = 0x1E02;
  17026. Engine._DECR = 0x1E03;
  17027. Engine._INVERT = 0x150A;
  17028. Engine._INCR_WRAP = 0x8507;
  17029. Engine._DECR_WRAP = 0x8508;
  17030. // Texture rescaling mode
  17031. Engine._SCALEMODE_FLOOR = 1;
  17032. Engine._SCALEMODE_NEAREST = 2;
  17033. Engine._SCALEMODE_CEILING = 3;
  17034. // Updatable statics so stick with vars here
  17035. /**
  17036. * Gets or sets the epsilon value used by collision engine
  17037. */
  17038. Engine.CollisionsEpsilon = 0.001;
  17039. /**
  17040. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17041. */
  17042. Engine.CodeRepository = "src/";
  17043. /**
  17044. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17045. */
  17046. Engine.ShadersRepository = "src/Shaders/";
  17047. return Engine;
  17048. }());
  17049. BABYLON.Engine = Engine;
  17050. })(BABYLON || (BABYLON = {}));
  17051. //# sourceMappingURL=babylon.engine.js.map
  17052. "use strict";
  17053. var BABYLON;
  17054. (function (BABYLON) {
  17055. /**
  17056. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17057. */
  17058. var Node = /** @class */ (function () {
  17059. /**
  17060. * Creates a new Node
  17061. * @param {string} name - the name and id to be given to this node
  17062. * @param {BABYLON.Scene} the scene this node will be added to
  17063. */
  17064. function Node(name, scene) {
  17065. if (scene === void 0) { scene = null; }
  17066. /**
  17067. * Gets or sets a string used to store user defined state for the node
  17068. */
  17069. this.state = "";
  17070. /**
  17071. * Gets or sets an object used to store user defined information for the node
  17072. */
  17073. this.metadata = null;
  17074. /**
  17075. * Gets or sets a boolean used to define if the node must be serialized
  17076. */
  17077. this.doNotSerialize = false;
  17078. /** @ignore */
  17079. this._isDisposed = false;
  17080. /**
  17081. * Gets a list of Animations associated with the node
  17082. */
  17083. this.animations = new Array();
  17084. this._ranges = {};
  17085. this._isEnabled = true;
  17086. this._isReady = true;
  17087. /** @ignore */
  17088. this._currentRenderId = -1;
  17089. this._parentRenderId = -1;
  17090. this._childRenderId = -1;
  17091. this._animationPropertiesOverride = null;
  17092. /**
  17093. * An event triggered when the mesh is disposed
  17094. */
  17095. this.onDisposeObservable = new BABYLON.Observable();
  17096. // Behaviors
  17097. this._behaviors = new Array();
  17098. this.name = name;
  17099. this.id = name;
  17100. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17101. this.uniqueId = this._scene.getUniqueId();
  17102. this._initCache();
  17103. }
  17104. /**
  17105. * Gets a boolean indicating if the node has been disposed
  17106. * @returns true if the node was disposed
  17107. */
  17108. Node.prototype.isDisposed = function () {
  17109. return this._isDisposed;
  17110. };
  17111. Object.defineProperty(Node.prototype, "parent", {
  17112. get: function () {
  17113. return this._parentNode;
  17114. },
  17115. /**
  17116. * Gets or sets the parent of the node
  17117. */
  17118. set: function (parent) {
  17119. if (this._parentNode === parent) {
  17120. return;
  17121. }
  17122. // Remove self from list of children of parent
  17123. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17124. var index = this._parentNode._children.indexOf(this);
  17125. if (index !== -1) {
  17126. this._parentNode._children.splice(index, 1);
  17127. }
  17128. }
  17129. // Store new parent
  17130. this._parentNode = parent;
  17131. // Add as child to new parent
  17132. if (this._parentNode) {
  17133. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17134. this._parentNode._children = new Array();
  17135. }
  17136. this._parentNode._children.push(this);
  17137. }
  17138. },
  17139. enumerable: true,
  17140. configurable: true
  17141. });
  17142. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17143. /**
  17144. * Gets or sets the animation properties override
  17145. */
  17146. get: function () {
  17147. return this._animationPropertiesOverride;
  17148. },
  17149. set: function (value) {
  17150. this._animationPropertiesOverride = value;
  17151. },
  17152. enumerable: true,
  17153. configurable: true
  17154. });
  17155. /**
  17156. * Gets a string idenfifying the name of the class
  17157. * @returns "Node" string
  17158. */
  17159. Node.prototype.getClassName = function () {
  17160. return "Node";
  17161. };
  17162. Object.defineProperty(Node.prototype, "onDispose", {
  17163. /**
  17164. * Sets a callback that will be raised when the node will be disposed
  17165. */
  17166. set: function (callback) {
  17167. if (this._onDisposeObserver) {
  17168. this.onDisposeObservable.remove(this._onDisposeObserver);
  17169. }
  17170. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17171. },
  17172. enumerable: true,
  17173. configurable: true
  17174. });
  17175. /**
  17176. * Gets the scene of the node
  17177. * @returns a {BABYLON.Scene}
  17178. */
  17179. Node.prototype.getScene = function () {
  17180. return this._scene;
  17181. };
  17182. /**
  17183. * Gets the engine of the node
  17184. * @returns a {BABYLON.Engine}
  17185. */
  17186. Node.prototype.getEngine = function () {
  17187. return this._scene.getEngine();
  17188. };
  17189. /**
  17190. * Attach a behavior to the node
  17191. * @see http://doc.babylonjs.com/features/behaviour
  17192. * @param behavior defines the behavior to attach
  17193. * @returns the current Node
  17194. */
  17195. Node.prototype.addBehavior = function (behavior) {
  17196. var _this = this;
  17197. var index = this._behaviors.indexOf(behavior);
  17198. if (index !== -1) {
  17199. return this;
  17200. }
  17201. behavior.init();
  17202. if (this._scene.isLoading) {
  17203. // We defer the attach when the scene will be loaded
  17204. var observer = this._scene.onDataLoadedObservable.add(function () {
  17205. behavior.attach(_this);
  17206. setTimeout(function () {
  17207. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17208. _this._scene.onDataLoadedObservable.remove(observer);
  17209. }, 0);
  17210. });
  17211. }
  17212. else {
  17213. behavior.attach(this);
  17214. }
  17215. this._behaviors.push(behavior);
  17216. return this;
  17217. };
  17218. /**
  17219. * Remove an attached behavior
  17220. * @see http://doc.babylonjs.com/features/behaviour
  17221. * @param behavior defines the behavior to attach
  17222. * @returns the current Node
  17223. */
  17224. Node.prototype.removeBehavior = function (behavior) {
  17225. var index = this._behaviors.indexOf(behavior);
  17226. if (index === -1) {
  17227. return this;
  17228. }
  17229. this._behaviors[index].detach();
  17230. this._behaviors.splice(index, 1);
  17231. return this;
  17232. };
  17233. Object.defineProperty(Node.prototype, "behaviors", {
  17234. /**
  17235. * Gets the list of attached behaviors
  17236. * @see http://doc.babylonjs.com/features/behaviour
  17237. */
  17238. get: function () {
  17239. return this._behaviors;
  17240. },
  17241. enumerable: true,
  17242. configurable: true
  17243. });
  17244. /**
  17245. * Gets an attached behavior by name
  17246. * @param name defines the name of the behavior to look for
  17247. * @see http://doc.babylonjs.com/features/behaviour
  17248. * @returns null if behavior was not found else the requested behavior
  17249. */
  17250. Node.prototype.getBehaviorByName = function (name) {
  17251. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17252. var behavior = _a[_i];
  17253. if (behavior.name === name) {
  17254. return behavior;
  17255. }
  17256. }
  17257. return null;
  17258. };
  17259. /**
  17260. * Returns the world matrix of the node
  17261. * @returns a matrix containing the node's world matrix
  17262. */
  17263. Node.prototype.getWorldMatrix = function () {
  17264. return BABYLON.Matrix.Identity();
  17265. };
  17266. // override it in derived class if you add new variables to the cache
  17267. // and call the parent class method
  17268. /** @ignore */
  17269. Node.prototype._initCache = function () {
  17270. this._cache = {};
  17271. this._cache.parent = undefined;
  17272. };
  17273. /** @ignore */
  17274. Node.prototype.updateCache = function (force) {
  17275. if (!force && this.isSynchronized())
  17276. return;
  17277. this._cache.parent = this.parent;
  17278. this._updateCache();
  17279. };
  17280. // override it in derived class if you add new variables to the cache
  17281. // and call the parent class method if !ignoreParentClass
  17282. /** @ignore */
  17283. Node.prototype._updateCache = function (ignoreParentClass) {
  17284. };
  17285. // override it in derived class if you add new variables to the cache
  17286. /** @ignore */
  17287. Node.prototype._isSynchronized = function () {
  17288. return true;
  17289. };
  17290. /** @ignore */
  17291. Node.prototype._markSyncedWithParent = function () {
  17292. if (this.parent) {
  17293. this._parentRenderId = this.parent._childRenderId;
  17294. }
  17295. };
  17296. /** @ignore */
  17297. Node.prototype.isSynchronizedWithParent = function () {
  17298. if (!this.parent) {
  17299. return true;
  17300. }
  17301. if (this._parentRenderId !== this.parent._childRenderId) {
  17302. return false;
  17303. }
  17304. return this.parent.isSynchronized();
  17305. };
  17306. /** @ignore */
  17307. Node.prototype.isSynchronized = function (updateCache) {
  17308. var check = this.hasNewParent();
  17309. check = check || !this.isSynchronizedWithParent();
  17310. check = check || !this._isSynchronized();
  17311. if (updateCache)
  17312. this.updateCache(true);
  17313. return !check;
  17314. };
  17315. /** @ignore */
  17316. Node.prototype.hasNewParent = function (update) {
  17317. if (this._cache.parent === this.parent)
  17318. return false;
  17319. if (update)
  17320. this._cache.parent = this.parent;
  17321. return true;
  17322. };
  17323. /**
  17324. * Is this node ready to be used/rendered
  17325. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17326. * @return true if the node is ready
  17327. */
  17328. Node.prototype.isReady = function (completeCheck) {
  17329. if (completeCheck === void 0) { completeCheck = false; }
  17330. return this._isReady;
  17331. };
  17332. /**
  17333. * Is this node enabled?
  17334. * 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
  17335. * @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
  17336. * @return whether this node (and its parent) is enabled
  17337. */
  17338. Node.prototype.isEnabled = function (checkAncestors) {
  17339. if (checkAncestors === void 0) { checkAncestors = true; }
  17340. if (checkAncestors === false) {
  17341. return this._isEnabled;
  17342. }
  17343. if (this._isEnabled === false) {
  17344. return false;
  17345. }
  17346. if (this.parent !== undefined && this.parent !== null) {
  17347. return this.parent.isEnabled(checkAncestors);
  17348. }
  17349. return true;
  17350. };
  17351. /**
  17352. * Set the enabled state of this node
  17353. * @param value defines the new enabled state
  17354. */
  17355. Node.prototype.setEnabled = function (value) {
  17356. this._isEnabled = value;
  17357. };
  17358. /**
  17359. * Is this node a descendant of the given node?
  17360. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17361. * @param ancestor defines the parent node to inspect
  17362. * @returns a boolean indicating if this node is a descendant of the given node
  17363. */
  17364. Node.prototype.isDescendantOf = function (ancestor) {
  17365. if (this.parent) {
  17366. if (this.parent === ancestor) {
  17367. return true;
  17368. }
  17369. return this.parent.isDescendantOf(ancestor);
  17370. }
  17371. return false;
  17372. };
  17373. /** @ignore */
  17374. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17375. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17376. if (!this._children) {
  17377. return;
  17378. }
  17379. for (var index = 0; index < this._children.length; index++) {
  17380. var item = this._children[index];
  17381. if (!predicate || predicate(item)) {
  17382. results.push(item);
  17383. }
  17384. if (!directDescendantsOnly) {
  17385. item._getDescendants(results, false, predicate);
  17386. }
  17387. }
  17388. };
  17389. /**
  17390. * Will return all nodes that have this node as ascendant
  17391. * @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
  17392. * @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
  17393. * @return all children nodes of all types
  17394. */
  17395. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17396. var results = new Array();
  17397. this._getDescendants(results, directDescendantsOnly, predicate);
  17398. return results;
  17399. };
  17400. /**
  17401. * Get all child-meshes of this node
  17402. * @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
  17403. * @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
  17404. * @returns an array of {BABYLON.AbstractMesh}
  17405. */
  17406. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17407. var results = [];
  17408. this._getDescendants(results, directDescendantsOnly, function (node) {
  17409. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17410. });
  17411. return results;
  17412. };
  17413. /**
  17414. * Get all child-transformNodes of this node
  17415. * @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
  17416. * @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
  17417. * @returns an array of {BABYLON.TransformNode}
  17418. */
  17419. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17420. var results = [];
  17421. this._getDescendants(results, directDescendantsOnly, function (node) {
  17422. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17423. });
  17424. return results;
  17425. };
  17426. /**
  17427. * Get all direct children of this node
  17428. * @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
  17429. * @returns an array of {BABYLON.Node}
  17430. */
  17431. Node.prototype.getChildren = function (predicate) {
  17432. return this.getDescendants(true, predicate);
  17433. };
  17434. /** @ignore */
  17435. Node.prototype._setReady = function (state) {
  17436. if (state === this._isReady) {
  17437. return;
  17438. }
  17439. if (!state) {
  17440. this._isReady = false;
  17441. return;
  17442. }
  17443. if (this.onReady) {
  17444. this.onReady(this);
  17445. }
  17446. this._isReady = true;
  17447. };
  17448. /**
  17449. * Get an animation by name
  17450. * @param name defines the name of the animation to look for
  17451. * @returns null if not found else the requested animation
  17452. */
  17453. Node.prototype.getAnimationByName = function (name) {
  17454. for (var i = 0; i < this.animations.length; i++) {
  17455. var animation = this.animations[i];
  17456. if (animation.name === name) {
  17457. return animation;
  17458. }
  17459. }
  17460. return null;
  17461. };
  17462. /**
  17463. * Creates an animation range for this node
  17464. * @param name defines the name of the range
  17465. * @param from defines the starting key
  17466. * @param to defines the end key
  17467. */
  17468. Node.prototype.createAnimationRange = function (name, from, to) {
  17469. // check name not already in use
  17470. if (!this._ranges[name]) {
  17471. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17472. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17473. if (this.animations[i]) {
  17474. this.animations[i].createRange(name, from, to);
  17475. }
  17476. }
  17477. }
  17478. };
  17479. /**
  17480. * Delete a specific animation range
  17481. * @param name defines the name of the range to delete
  17482. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17483. */
  17484. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17485. if (deleteFrames === void 0) { deleteFrames = true; }
  17486. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17487. if (this.animations[i]) {
  17488. this.animations[i].deleteRange(name, deleteFrames);
  17489. }
  17490. }
  17491. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17492. };
  17493. /**
  17494. * Get an animation range by name
  17495. * @param name defines the name of the animation range to look for
  17496. * @returns null if not found else the requested animation range
  17497. */
  17498. Node.prototype.getAnimationRange = function (name) {
  17499. return this._ranges[name];
  17500. };
  17501. /**
  17502. * Will start the animation sequence
  17503. * @param name defines the range frames for animation sequence
  17504. * @param loop defines if the animation should loop (false by default)
  17505. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17506. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17507. * @returns the object created for this animation. If range does not exist, it will return null
  17508. */
  17509. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17510. var range = this.getAnimationRange(name);
  17511. if (!range) {
  17512. return null;
  17513. }
  17514. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17515. };
  17516. /**
  17517. * Serialize animation ranges into a JSON compatible object
  17518. * @returns serialization object
  17519. */
  17520. Node.prototype.serializeAnimationRanges = function () {
  17521. var serializationRanges = [];
  17522. for (var name in this._ranges) {
  17523. var localRange = this._ranges[name];
  17524. if (!localRange) {
  17525. continue;
  17526. }
  17527. var range = {};
  17528. range.name = name;
  17529. range.from = localRange.from;
  17530. range.to = localRange.to;
  17531. serializationRanges.push(range);
  17532. }
  17533. return serializationRanges;
  17534. };
  17535. /**
  17536. * Computes the world matrix of the node
  17537. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17538. * @returns the world matrix
  17539. */
  17540. Node.prototype.computeWorldMatrix = function (force) {
  17541. return BABYLON.Matrix.Identity();
  17542. };
  17543. /**
  17544. * Releases resources associated with this node.
  17545. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17546. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17547. */
  17548. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17549. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17550. if (!doNotRecurse) {
  17551. var nodes = this.getDescendants(true);
  17552. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17553. var node = nodes_1[_i];
  17554. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17555. }
  17556. }
  17557. else {
  17558. var transformNodes = this.getChildTransformNodes(true);
  17559. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17560. var transformNode = transformNodes_1[_a];
  17561. transformNode.parent = null;
  17562. transformNode.computeWorldMatrix(true);
  17563. }
  17564. }
  17565. this.parent = null;
  17566. // Callback
  17567. this.onDisposeObservable.notifyObservers(this);
  17568. this.onDisposeObservable.clear();
  17569. // Behaviors
  17570. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17571. var behavior = _c[_b];
  17572. behavior.detach();
  17573. }
  17574. this._behaviors = [];
  17575. this._isDisposed = true;
  17576. };
  17577. /**
  17578. * Parse animation range data from a serialization object and store them into a given node
  17579. * @param node defines where to store the animation ranges
  17580. * @param parsedNode defines the serialization object to read data from
  17581. * @param scene defines the hosting scene
  17582. */
  17583. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17584. if (parsedNode.ranges) {
  17585. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17586. var data = parsedNode.ranges[index];
  17587. node.createAnimationRange(data.name, data.from, data.to);
  17588. }
  17589. }
  17590. };
  17591. __decorate([
  17592. BABYLON.serialize()
  17593. ], Node.prototype, "name", void 0);
  17594. __decorate([
  17595. BABYLON.serialize()
  17596. ], Node.prototype, "id", void 0);
  17597. __decorate([
  17598. BABYLON.serialize()
  17599. ], Node.prototype, "uniqueId", void 0);
  17600. __decorate([
  17601. BABYLON.serialize()
  17602. ], Node.prototype, "state", void 0);
  17603. __decorate([
  17604. BABYLON.serialize()
  17605. ], Node.prototype, "metadata", void 0);
  17606. return Node;
  17607. }());
  17608. BABYLON.Node = Node;
  17609. })(BABYLON || (BABYLON = {}));
  17610. //# sourceMappingURL=babylon.node.js.map
  17611. "use strict";
  17612. var BABYLON;
  17613. (function (BABYLON) {
  17614. var BoundingSphere = /** @class */ (function () {
  17615. function BoundingSphere(minimum, maximum) {
  17616. this.minimum = minimum;
  17617. this.maximum = maximum;
  17618. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17619. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  17620. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  17621. this.radius = distance * 0.5;
  17622. this.centerWorld = BABYLON.Vector3.Zero();
  17623. this._update(BABYLON.Matrix.Identity());
  17624. }
  17625. // Methods
  17626. BoundingSphere.prototype._update = function (world) {
  17627. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17628. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17629. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17630. };
  17631. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17632. for (var i = 0; i < 6; i++) {
  17633. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17634. return false;
  17635. }
  17636. return true;
  17637. };
  17638. BoundingSphere.prototype.intersectsPoint = function (point) {
  17639. var x = this.centerWorld.x - point.x;
  17640. var y = this.centerWorld.y - point.y;
  17641. var z = this.centerWorld.z - point.z;
  17642. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17643. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17644. return false;
  17645. return true;
  17646. };
  17647. // Statics
  17648. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17649. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17650. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17651. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17652. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17653. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17654. return false;
  17655. return true;
  17656. };
  17657. return BoundingSphere;
  17658. }());
  17659. BABYLON.BoundingSphere = BoundingSphere;
  17660. })(BABYLON || (BABYLON = {}));
  17661. //# sourceMappingURL=babylon.boundingSphere.js.map
  17662. "use strict";
  17663. var BABYLON;
  17664. (function (BABYLON) {
  17665. var BoundingBox = /** @class */ (function () {
  17666. function BoundingBox(minimum, maximum) {
  17667. this.minimum = minimum;
  17668. this.maximum = maximum;
  17669. this.vectors = new Array();
  17670. this.vectorsWorld = new Array();
  17671. // Bounding vectors
  17672. this.vectors.push(this.minimum.clone());
  17673. this.vectors.push(this.maximum.clone());
  17674. this.vectors.push(this.minimum.clone());
  17675. this.vectors[2].x = this.maximum.x;
  17676. this.vectors.push(this.minimum.clone());
  17677. this.vectors[3].y = this.maximum.y;
  17678. this.vectors.push(this.minimum.clone());
  17679. this.vectors[4].z = this.maximum.z;
  17680. this.vectors.push(this.maximum.clone());
  17681. this.vectors[5].z = this.minimum.z;
  17682. this.vectors.push(this.maximum.clone());
  17683. this.vectors[6].x = this.minimum.x;
  17684. this.vectors.push(this.maximum.clone());
  17685. this.vectors[7].y = this.minimum.y;
  17686. // OBB
  17687. this.center = this.maximum.add(this.minimum).scale(0.5);
  17688. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17689. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17690. // World
  17691. for (var index = 0; index < this.vectors.length; index++) {
  17692. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17693. }
  17694. this.minimumWorld = BABYLON.Vector3.Zero();
  17695. this.maximumWorld = BABYLON.Vector3.Zero();
  17696. this.centerWorld = BABYLON.Vector3.Zero();
  17697. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17698. this._update(BABYLON.Matrix.Identity());
  17699. }
  17700. // Methods
  17701. BoundingBox.prototype.getWorldMatrix = function () {
  17702. return this._worldMatrix;
  17703. };
  17704. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17705. this._worldMatrix.copyFrom(matrix);
  17706. return this;
  17707. };
  17708. BoundingBox.prototype._update = function (world) {
  17709. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17710. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17711. for (var index = 0; index < this.vectors.length; index++) {
  17712. var v = this.vectorsWorld[index];
  17713. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17714. if (v.x < this.minimumWorld.x)
  17715. this.minimumWorld.x = v.x;
  17716. if (v.y < this.minimumWorld.y)
  17717. this.minimumWorld.y = v.y;
  17718. if (v.z < this.minimumWorld.z)
  17719. this.minimumWorld.z = v.z;
  17720. if (v.x > this.maximumWorld.x)
  17721. this.maximumWorld.x = v.x;
  17722. if (v.y > this.maximumWorld.y)
  17723. this.maximumWorld.y = v.y;
  17724. if (v.z > this.maximumWorld.z)
  17725. this.maximumWorld.z = v.z;
  17726. }
  17727. // Extend
  17728. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17729. this.extendSizeWorld.scaleInPlace(0.5);
  17730. // OBB
  17731. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17732. this.centerWorld.scaleInPlace(0.5);
  17733. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17734. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17735. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17736. this._worldMatrix = world;
  17737. };
  17738. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17739. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17740. };
  17741. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17742. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17743. };
  17744. BoundingBox.prototype.intersectsPoint = function (point) {
  17745. var delta = -BABYLON.Epsilon;
  17746. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17747. return false;
  17748. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17749. return false;
  17750. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17751. return false;
  17752. return true;
  17753. };
  17754. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17755. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17756. };
  17757. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17758. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17759. return false;
  17760. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17761. return false;
  17762. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17763. return false;
  17764. return true;
  17765. };
  17766. // Statics
  17767. BoundingBox.Intersects = function (box0, box1) {
  17768. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17769. return false;
  17770. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17771. return false;
  17772. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17773. return false;
  17774. return true;
  17775. };
  17776. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17777. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17778. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17779. return (num <= (sphereRadius * sphereRadius));
  17780. };
  17781. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17782. for (var p = 0; p < 6; p++) {
  17783. for (var i = 0; i < 8; i++) {
  17784. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17785. return false;
  17786. }
  17787. }
  17788. }
  17789. return true;
  17790. };
  17791. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17792. for (var p = 0; p < 6; p++) {
  17793. var inCount = 8;
  17794. for (var i = 0; i < 8; i++) {
  17795. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17796. --inCount;
  17797. }
  17798. else {
  17799. break;
  17800. }
  17801. }
  17802. if (inCount === 0)
  17803. return false;
  17804. }
  17805. return true;
  17806. };
  17807. return BoundingBox;
  17808. }());
  17809. BABYLON.BoundingBox = BoundingBox;
  17810. })(BABYLON || (BABYLON = {}));
  17811. //# sourceMappingURL=babylon.boundingBox.js.map
  17812. "use strict";
  17813. var BABYLON;
  17814. (function (BABYLON) {
  17815. var computeBoxExtents = function (axis, box) {
  17816. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  17817. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  17818. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  17819. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  17820. var r = r0 + r1 + r2;
  17821. return {
  17822. min: p - r,
  17823. max: p + r
  17824. };
  17825. };
  17826. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  17827. var axisOverlap = function (axis, box0, box1) {
  17828. var result0 = computeBoxExtents(axis, box0);
  17829. var result1 = computeBoxExtents(axis, box1);
  17830. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  17831. };
  17832. var BoundingInfo = /** @class */ (function () {
  17833. function BoundingInfo(minimum, maximum) {
  17834. this.minimum = minimum;
  17835. this.maximum = maximum;
  17836. this._isLocked = false;
  17837. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  17838. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  17839. }
  17840. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  17841. get: function () {
  17842. return this._isLocked;
  17843. },
  17844. set: function (value) {
  17845. this._isLocked = value;
  17846. },
  17847. enumerable: true,
  17848. configurable: true
  17849. });
  17850. // Methods
  17851. BoundingInfo.prototype.update = function (world) {
  17852. if (this._isLocked) {
  17853. return;
  17854. }
  17855. this.boundingBox._update(world);
  17856. this.boundingSphere._update(world);
  17857. };
  17858. /**
  17859. * Recreate the bounding info to be centered around a specific point given a specific extend.
  17860. * @param center New center of the bounding info
  17861. * @param extend New extend of the bounding info
  17862. */
  17863. BoundingInfo.prototype.centerOn = function (center, extend) {
  17864. this.minimum = center.subtract(extend);
  17865. this.maximum = center.add(extend);
  17866. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  17867. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  17868. return this;
  17869. };
  17870. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  17871. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  17872. return false;
  17873. return this.boundingBox.isInFrustum(frustumPlanes);
  17874. };
  17875. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  17876. /**
  17877. * Gets the world distance between the min and max points of the bounding box
  17878. */
  17879. get: function () {
  17880. var boundingBox = this.boundingBox;
  17881. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  17882. return size.length();
  17883. },
  17884. enumerable: true,
  17885. configurable: true
  17886. });
  17887. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17888. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  17889. };
  17890. BoundingInfo.prototype._checkCollision = function (collider) {
  17891. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  17892. };
  17893. BoundingInfo.prototype.intersectsPoint = function (point) {
  17894. if (!this.boundingSphere.centerWorld) {
  17895. return false;
  17896. }
  17897. if (!this.boundingSphere.intersectsPoint(point)) {
  17898. return false;
  17899. }
  17900. if (!this.boundingBox.intersectsPoint(point)) {
  17901. return false;
  17902. }
  17903. return true;
  17904. };
  17905. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  17906. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  17907. return false;
  17908. }
  17909. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  17910. return false;
  17911. }
  17912. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  17913. return false;
  17914. }
  17915. if (!precise) {
  17916. return true;
  17917. }
  17918. var box0 = this.boundingBox;
  17919. var box1 = boundingInfo.boundingBox;
  17920. if (!axisOverlap(box0.directions[0], box0, box1))
  17921. return false;
  17922. if (!axisOverlap(box0.directions[1], box0, box1))
  17923. return false;
  17924. if (!axisOverlap(box0.directions[2], box0, box1))
  17925. return false;
  17926. if (!axisOverlap(box1.directions[0], box0, box1))
  17927. return false;
  17928. if (!axisOverlap(box1.directions[1], box0, box1))
  17929. return false;
  17930. if (!axisOverlap(box1.directions[2], box0, box1))
  17931. return false;
  17932. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  17933. return false;
  17934. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  17935. return false;
  17936. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  17937. return false;
  17938. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  17939. return false;
  17940. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  17941. return false;
  17942. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  17943. return false;
  17944. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  17945. return false;
  17946. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  17947. return false;
  17948. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  17949. return false;
  17950. return true;
  17951. };
  17952. return BoundingInfo;
  17953. }());
  17954. BABYLON.BoundingInfo = BoundingInfo;
  17955. })(BABYLON || (BABYLON = {}));
  17956. //# sourceMappingURL=babylon.boundingInfo.js.map
  17957. "use strict";
  17958. var BABYLON;
  17959. (function (BABYLON) {
  17960. var TransformNode = /** @class */ (function (_super) {
  17961. __extends(TransformNode, _super);
  17962. function TransformNode(name, scene, isPure) {
  17963. if (scene === void 0) { scene = null; }
  17964. if (isPure === void 0) { isPure = true; }
  17965. var _this = _super.call(this, name, scene) || this;
  17966. _this._forward = new BABYLON.Vector3(0, 0, 1);
  17967. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  17968. _this._up = new BABYLON.Vector3(0, 1, 0);
  17969. _this._right = new BABYLON.Vector3(1, 0, 0);
  17970. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  17971. // Properties
  17972. _this._rotation = BABYLON.Vector3.Zero();
  17973. _this._scaling = BABYLON.Vector3.One();
  17974. _this._isDirty = false;
  17975. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  17976. _this.scalingDeterminant = 1;
  17977. _this.infiniteDistance = false;
  17978. _this.position = BABYLON.Vector3.Zero();
  17979. _this._localWorld = BABYLON.Matrix.Zero();
  17980. _this._worldMatrix = BABYLON.Matrix.Zero();
  17981. _this._worldMatrixDeterminant = 0;
  17982. _this._absolutePosition = BABYLON.Vector3.Zero();
  17983. _this._pivotMatrix = BABYLON.Matrix.Identity();
  17984. _this._postMultiplyPivotMatrix = false;
  17985. _this._isWorldMatrixFrozen = false;
  17986. /**
  17987. * An event triggered after the world matrix is updated
  17988. */
  17989. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  17990. _this._nonUniformScaling = false;
  17991. if (isPure) {
  17992. _this.getScene().addTransformNode(_this);
  17993. }
  17994. return _this;
  17995. }
  17996. /**
  17997. * Gets a string idenfifying the name of the class
  17998. * @returns "TransformNode" string
  17999. */
  18000. TransformNode.prototype.getClassName = function () {
  18001. return "TransformNode";
  18002. };
  18003. Object.defineProperty(TransformNode.prototype, "rotation", {
  18004. /**
  18005. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18006. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18007. * Default : (0.0, 0.0, 0.0)
  18008. */
  18009. get: function () {
  18010. return this._rotation;
  18011. },
  18012. set: function (newRotation) {
  18013. this._rotation = newRotation;
  18014. },
  18015. enumerable: true,
  18016. configurable: true
  18017. });
  18018. Object.defineProperty(TransformNode.prototype, "scaling", {
  18019. /**
  18020. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18021. * Default : (1.0, 1.0, 1.0)
  18022. */
  18023. get: function () {
  18024. return this._scaling;
  18025. },
  18026. /**
  18027. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18028. * Default : (1.0, 1.0, 1.0)
  18029. */
  18030. set: function (newScaling) {
  18031. this._scaling = newScaling;
  18032. },
  18033. enumerable: true,
  18034. configurable: true
  18035. });
  18036. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18037. /**
  18038. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18039. * It's null by default.
  18040. * 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)
  18041. */
  18042. get: function () {
  18043. return this._rotationQuaternion;
  18044. },
  18045. set: function (quaternion) {
  18046. this._rotationQuaternion = quaternion;
  18047. //reset the rotation vector.
  18048. if (quaternion && this.rotation.length()) {
  18049. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18050. }
  18051. },
  18052. enumerable: true,
  18053. configurable: true
  18054. });
  18055. Object.defineProperty(TransformNode.prototype, "forward", {
  18056. /**
  18057. * The forward direction of that transform in world space.
  18058. */
  18059. get: function () {
  18060. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18061. },
  18062. enumerable: true,
  18063. configurable: true
  18064. });
  18065. Object.defineProperty(TransformNode.prototype, "up", {
  18066. /**
  18067. * The up direction of that transform in world space.
  18068. */
  18069. get: function () {
  18070. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18071. },
  18072. enumerable: true,
  18073. configurable: true
  18074. });
  18075. Object.defineProperty(TransformNode.prototype, "right", {
  18076. /**
  18077. * The right direction of that transform in world space.
  18078. */
  18079. get: function () {
  18080. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18081. },
  18082. enumerable: true,
  18083. configurable: true
  18084. });
  18085. /**
  18086. * Returns the latest update of the World matrix
  18087. * Returns a Matrix.
  18088. */
  18089. TransformNode.prototype.getWorldMatrix = function () {
  18090. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18091. this.computeWorldMatrix();
  18092. }
  18093. return this._worldMatrix;
  18094. };
  18095. /**
  18096. * Returns the latest update of the World matrix determinant.
  18097. */
  18098. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18099. return this._worldMatrixDeterminant;
  18100. };
  18101. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18102. /**
  18103. * Returns directly the latest state of the mesh World matrix.
  18104. * A Matrix is returned.
  18105. */
  18106. get: function () {
  18107. return this._worldMatrix;
  18108. },
  18109. enumerable: true,
  18110. configurable: true
  18111. });
  18112. /**
  18113. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18114. * Returns the TransformNode.
  18115. */
  18116. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18117. this._poseMatrix.copyFrom(matrix);
  18118. return this;
  18119. };
  18120. /**
  18121. * Returns the mesh Pose matrix.
  18122. * Returned object : Matrix
  18123. */
  18124. TransformNode.prototype.getPoseMatrix = function () {
  18125. return this._poseMatrix;
  18126. };
  18127. TransformNode.prototype._isSynchronized = function () {
  18128. if (this._isDirty) {
  18129. return false;
  18130. }
  18131. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18132. return false;
  18133. if (this._cache.pivotMatrixUpdated) {
  18134. return false;
  18135. }
  18136. if (this.infiniteDistance) {
  18137. return false;
  18138. }
  18139. if (!this._cache.position.equals(this.position))
  18140. return false;
  18141. if (this.rotationQuaternion) {
  18142. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18143. return false;
  18144. }
  18145. if (!this._cache.rotation.equals(this.rotation))
  18146. return false;
  18147. if (!this._cache.scaling.equals(this.scaling))
  18148. return false;
  18149. return true;
  18150. };
  18151. TransformNode.prototype._initCache = function () {
  18152. _super.prototype._initCache.call(this);
  18153. this._cache.localMatrixUpdated = false;
  18154. this._cache.position = BABYLON.Vector3.Zero();
  18155. this._cache.scaling = BABYLON.Vector3.Zero();
  18156. this._cache.rotation = BABYLON.Vector3.Zero();
  18157. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18158. this._cache.billboardMode = -1;
  18159. };
  18160. TransformNode.prototype.markAsDirty = function (property) {
  18161. if (property === "rotation") {
  18162. this.rotationQuaternion = null;
  18163. }
  18164. this._currentRenderId = Number.MAX_VALUE;
  18165. this._isDirty = true;
  18166. return this;
  18167. };
  18168. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18169. /**
  18170. * Returns the current mesh absolute position.
  18171. * Retuns a Vector3.
  18172. */
  18173. get: function () {
  18174. return this._absolutePosition;
  18175. },
  18176. enumerable: true,
  18177. configurable: true
  18178. });
  18179. /**
  18180. * Sets a new matrix to apply before all other transformation
  18181. * @param matrix defines the transform matrix
  18182. * @returns the current TransformNode
  18183. */
  18184. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18185. return this.setPivotMatrix(matrix, false);
  18186. };
  18187. /**
  18188. * Sets a new pivot matrix to the current node
  18189. * @param matrix defines the new pivot matrix to use
  18190. * @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
  18191. * @returns the current TransformNode
  18192. */
  18193. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18194. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18195. this._pivotMatrix = matrix.clone();
  18196. this._cache.pivotMatrixUpdated = true;
  18197. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18198. if (this._postMultiplyPivotMatrix) {
  18199. if (!this._pivotMatrixInverse) {
  18200. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18201. }
  18202. else {
  18203. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18204. }
  18205. }
  18206. return this;
  18207. };
  18208. /**
  18209. * Returns the mesh pivot matrix.
  18210. * Default : Identity.
  18211. * A Matrix is returned.
  18212. */
  18213. TransformNode.prototype.getPivotMatrix = function () {
  18214. return this._pivotMatrix;
  18215. };
  18216. /**
  18217. * Prevents the World matrix to be computed any longer.
  18218. * Returns the TransformNode.
  18219. */
  18220. TransformNode.prototype.freezeWorldMatrix = function () {
  18221. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18222. this.computeWorldMatrix(true);
  18223. this._isWorldMatrixFrozen = true;
  18224. return this;
  18225. };
  18226. /**
  18227. * Allows back the World matrix computation.
  18228. * Returns the TransformNode.
  18229. */
  18230. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18231. this._isWorldMatrixFrozen = false;
  18232. this.computeWorldMatrix(true);
  18233. return this;
  18234. };
  18235. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18236. /**
  18237. * True if the World matrix has been frozen.
  18238. * Returns a boolean.
  18239. */
  18240. get: function () {
  18241. return this._isWorldMatrixFrozen;
  18242. },
  18243. enumerable: true,
  18244. configurable: true
  18245. });
  18246. /**
  18247. * Retuns the mesh absolute position in the World.
  18248. * Returns a Vector3.
  18249. */
  18250. TransformNode.prototype.getAbsolutePosition = function () {
  18251. this.computeWorldMatrix();
  18252. return this._absolutePosition;
  18253. };
  18254. /**
  18255. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18256. * Returns the TransformNode.
  18257. */
  18258. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18259. if (!absolutePosition) {
  18260. return this;
  18261. }
  18262. var absolutePositionX;
  18263. var absolutePositionY;
  18264. var absolutePositionZ;
  18265. if (absolutePosition.x === undefined) {
  18266. if (arguments.length < 3) {
  18267. return this;
  18268. }
  18269. absolutePositionX = arguments[0];
  18270. absolutePositionY = arguments[1];
  18271. absolutePositionZ = arguments[2];
  18272. }
  18273. else {
  18274. absolutePositionX = absolutePosition.x;
  18275. absolutePositionY = absolutePosition.y;
  18276. absolutePositionZ = absolutePosition.z;
  18277. }
  18278. if (this.parent) {
  18279. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18280. invertParentWorldMatrix.invert();
  18281. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18282. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18283. }
  18284. else {
  18285. this.position.x = absolutePositionX;
  18286. this.position.y = absolutePositionY;
  18287. this.position.z = absolutePositionZ;
  18288. }
  18289. return this;
  18290. };
  18291. /**
  18292. * Sets the mesh position in its local space.
  18293. * Returns the TransformNode.
  18294. */
  18295. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18296. this.computeWorldMatrix();
  18297. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18298. return this;
  18299. };
  18300. /**
  18301. * Returns the mesh position in the local space from the current World matrix values.
  18302. * Returns a new Vector3.
  18303. */
  18304. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18305. this.computeWorldMatrix();
  18306. var invLocalWorldMatrix = this._localWorld.clone();
  18307. invLocalWorldMatrix.invert();
  18308. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18309. };
  18310. /**
  18311. * Translates the mesh along the passed Vector3 in its local space.
  18312. * Returns the TransformNode.
  18313. */
  18314. TransformNode.prototype.locallyTranslate = function (vector3) {
  18315. this.computeWorldMatrix(true);
  18316. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18317. return this;
  18318. };
  18319. /**
  18320. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18321. * @param targetPoint the position (must be in same space as current mesh) to look at
  18322. * @param yawCor optional yaw (y-axis) correction in radians
  18323. * @param pitchCor optional pitch (x-axis) correction in radians
  18324. * @param rollCor optional roll (z-axis) correction in radians
  18325. * @param space the choosen space of the target
  18326. * @returns the TransformNode.
  18327. */
  18328. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18329. if (yawCor === void 0) { yawCor = 0; }
  18330. if (pitchCor === void 0) { pitchCor = 0; }
  18331. if (rollCor === void 0) { rollCor = 0; }
  18332. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18333. var dv = TransformNode._lookAtVectorCache;
  18334. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18335. targetPoint.subtractToRef(pos, dv);
  18336. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18337. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18338. var pitch = Math.atan2(dv.y, len);
  18339. if (this.rotationQuaternion) {
  18340. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18341. }
  18342. else {
  18343. this.rotation.x = pitch + pitchCor;
  18344. this.rotation.y = yaw + yawCor;
  18345. this.rotation.z = rollCor;
  18346. }
  18347. return this;
  18348. };
  18349. /**
  18350. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18351. * This Vector3 is expressed in the World space.
  18352. */
  18353. TransformNode.prototype.getDirection = function (localAxis) {
  18354. var result = BABYLON.Vector3.Zero();
  18355. this.getDirectionToRef(localAxis, result);
  18356. return result;
  18357. };
  18358. /**
  18359. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18360. * localAxis is expressed in the mesh local space.
  18361. * result is computed in the Wordl space from the mesh World matrix.
  18362. * Returns the TransformNode.
  18363. */
  18364. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18365. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18366. return this;
  18367. };
  18368. /**
  18369. * Sets a new pivot point to the current node
  18370. * @param point defines the new pivot point to use
  18371. * @param space defines if the point is in world or local space (local by default)
  18372. * @returns the current TransformNode
  18373. */
  18374. TransformNode.prototype.setPivotPoint = function (point, space) {
  18375. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18376. if (this.getScene().getRenderId() == 0) {
  18377. this.computeWorldMatrix(true);
  18378. }
  18379. var wm = this.getWorldMatrix();
  18380. if (space == BABYLON.Space.WORLD) {
  18381. var tmat = BABYLON.Tmp.Matrix[0];
  18382. wm.invertToRef(tmat);
  18383. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18384. }
  18385. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18386. };
  18387. /**
  18388. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18389. */
  18390. TransformNode.prototype.getPivotPoint = function () {
  18391. var point = BABYLON.Vector3.Zero();
  18392. this.getPivotPointToRef(point);
  18393. return point;
  18394. };
  18395. /**
  18396. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18397. * Returns the TransformNode.
  18398. */
  18399. TransformNode.prototype.getPivotPointToRef = function (result) {
  18400. result.x = -this._pivotMatrix.m[12];
  18401. result.y = -this._pivotMatrix.m[13];
  18402. result.z = -this._pivotMatrix.m[14];
  18403. return this;
  18404. };
  18405. /**
  18406. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18407. */
  18408. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18409. var point = BABYLON.Vector3.Zero();
  18410. this.getAbsolutePivotPointToRef(point);
  18411. return point;
  18412. };
  18413. /**
  18414. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18415. * Returns the TransformNode.
  18416. */
  18417. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18418. result.x = this._pivotMatrix.m[12];
  18419. result.y = this._pivotMatrix.m[13];
  18420. result.z = this._pivotMatrix.m[14];
  18421. this.getPivotPointToRef(result);
  18422. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18423. return this;
  18424. };
  18425. /**
  18426. * Defines the passed node as the parent of the current node.
  18427. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18428. * Returns the TransformNode.
  18429. */
  18430. TransformNode.prototype.setParent = function (node) {
  18431. if (node === null) {
  18432. var rotation = BABYLON.Tmp.Quaternion[0];
  18433. var position = BABYLON.Tmp.Vector3[0];
  18434. var scale = BABYLON.Tmp.Vector3[1];
  18435. if (this.parent && this.parent.computeWorldMatrix) {
  18436. this.parent.computeWorldMatrix(true);
  18437. }
  18438. this.computeWorldMatrix(true);
  18439. this.getWorldMatrix().decompose(scale, rotation, position);
  18440. if (this.rotationQuaternion) {
  18441. this.rotationQuaternion.copyFrom(rotation);
  18442. }
  18443. else {
  18444. rotation.toEulerAnglesToRef(this.rotation);
  18445. }
  18446. this.scaling.x = scale.x;
  18447. this.scaling.y = scale.y;
  18448. this.scaling.z = scale.z;
  18449. this.position.x = position.x;
  18450. this.position.y = position.y;
  18451. this.position.z = position.z;
  18452. }
  18453. else {
  18454. var rotation = BABYLON.Tmp.Quaternion[0];
  18455. var position = BABYLON.Tmp.Vector3[0];
  18456. var scale = BABYLON.Tmp.Vector3[1];
  18457. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18458. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18459. this.computeWorldMatrix(true);
  18460. node.computeWorldMatrix(true);
  18461. node.getWorldMatrix().invertToRef(invParentMatrix);
  18462. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18463. diffMatrix.decompose(scale, rotation, position);
  18464. if (this.rotationQuaternion) {
  18465. this.rotationQuaternion.copyFrom(rotation);
  18466. }
  18467. else {
  18468. rotation.toEulerAnglesToRef(this.rotation);
  18469. }
  18470. this.position.x = position.x;
  18471. this.position.y = position.y;
  18472. this.position.z = position.z;
  18473. this.scaling.x = scale.x;
  18474. this.scaling.y = scale.y;
  18475. this.scaling.z = scale.z;
  18476. }
  18477. this.parent = node;
  18478. return this;
  18479. };
  18480. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18481. get: function () {
  18482. return this._nonUniformScaling;
  18483. },
  18484. enumerable: true,
  18485. configurable: true
  18486. });
  18487. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18488. if (this._nonUniformScaling === value) {
  18489. return false;
  18490. }
  18491. this._nonUniformScaling = true;
  18492. return true;
  18493. };
  18494. /**
  18495. * Attach the current TransformNode to another TransformNode associated with a bone
  18496. * @param bone Bone affecting the TransformNode
  18497. * @param affectedTransformNode TransformNode associated with the bone
  18498. */
  18499. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18500. this._transformToBoneReferal = affectedTransformNode;
  18501. this.parent = bone;
  18502. if (bone.getWorldMatrix().determinant() < 0) {
  18503. this.scalingDeterminant *= -1;
  18504. }
  18505. return this;
  18506. };
  18507. TransformNode.prototype.detachFromBone = function () {
  18508. if (!this.parent) {
  18509. return this;
  18510. }
  18511. if (this.parent.getWorldMatrix().determinant() < 0) {
  18512. this.scalingDeterminant *= -1;
  18513. }
  18514. this._transformToBoneReferal = null;
  18515. this.parent = null;
  18516. return this;
  18517. };
  18518. /**
  18519. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18520. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18521. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18522. * The passed axis is also normalized.
  18523. * Returns the TransformNode.
  18524. */
  18525. TransformNode.prototype.rotate = function (axis, amount, space) {
  18526. axis.normalize();
  18527. if (!this.rotationQuaternion) {
  18528. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18529. this.rotation = BABYLON.Vector3.Zero();
  18530. }
  18531. var rotationQuaternion;
  18532. if (!space || space === BABYLON.Space.LOCAL) {
  18533. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18534. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18535. }
  18536. else {
  18537. if (this.parent) {
  18538. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18539. invertParentWorldMatrix.invert();
  18540. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18541. }
  18542. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18543. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18544. }
  18545. return this;
  18546. };
  18547. /**
  18548. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18549. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18550. * The passed axis is also normalized.
  18551. * Returns the TransformNode.
  18552. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18553. */
  18554. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18555. axis.normalize();
  18556. if (!this.rotationQuaternion) {
  18557. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18558. this.rotation.copyFromFloats(0, 0, 0);
  18559. }
  18560. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18561. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18562. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18563. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18564. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18565. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18566. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18567. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18568. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18569. return this;
  18570. };
  18571. /**
  18572. * Translates the mesh along the axis vector for the passed distance in the given space.
  18573. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18574. * Returns the TransformNode.
  18575. */
  18576. TransformNode.prototype.translate = function (axis, distance, space) {
  18577. var displacementVector = axis.scale(distance);
  18578. if (!space || space === BABYLON.Space.LOCAL) {
  18579. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18580. this.setPositionWithLocalVector(tempV3);
  18581. }
  18582. else {
  18583. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18584. }
  18585. return this;
  18586. };
  18587. /**
  18588. * Adds a rotation step to the mesh current rotation.
  18589. * x, y, z are Euler angles expressed in radians.
  18590. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18591. * This means this rotation is made in the mesh local space only.
  18592. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18593. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18594. * ```javascript
  18595. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18596. * ```
  18597. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18598. * 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.
  18599. * Returns the TransformNode.
  18600. */
  18601. TransformNode.prototype.addRotation = function (x, y, z) {
  18602. var rotationQuaternion;
  18603. if (this.rotationQuaternion) {
  18604. rotationQuaternion = this.rotationQuaternion;
  18605. }
  18606. else {
  18607. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18608. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18609. }
  18610. var accumulation = BABYLON.Tmp.Quaternion[0];
  18611. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18612. rotationQuaternion.multiplyInPlace(accumulation);
  18613. if (!this.rotationQuaternion) {
  18614. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18615. }
  18616. return this;
  18617. };
  18618. /**
  18619. * Computes the mesh World matrix and returns it.
  18620. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18621. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18622. * If the parameter `force`is set to `true`, the actual computation is done.
  18623. * Returns the mesh World Matrix.
  18624. */
  18625. TransformNode.prototype.computeWorldMatrix = function (force) {
  18626. if (this._isWorldMatrixFrozen) {
  18627. return this._worldMatrix;
  18628. }
  18629. if (!force && this.isSynchronized(true)) {
  18630. this._currentRenderId = this.getScene().getRenderId();
  18631. return this._worldMatrix;
  18632. }
  18633. this._cache.position.copyFrom(this.position);
  18634. this._cache.scaling.copyFrom(this.scaling);
  18635. this._cache.pivotMatrixUpdated = false;
  18636. this._cache.billboardMode = this.billboardMode;
  18637. this._currentRenderId = this.getScene().getRenderId();
  18638. this._childRenderId = this.getScene().getRenderId();
  18639. this._isDirty = false;
  18640. // Scaling
  18641. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18642. // Rotation
  18643. //rotate, if quaternion is set and rotation was used
  18644. if (this.rotationQuaternion) {
  18645. var len = this.rotation.length();
  18646. if (len) {
  18647. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18648. this.rotation.copyFromFloats(0, 0, 0);
  18649. }
  18650. }
  18651. if (this.rotationQuaternion) {
  18652. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18653. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18654. }
  18655. else {
  18656. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18657. this._cache.rotation.copyFrom(this.rotation);
  18658. }
  18659. // Translation
  18660. var camera = this.getScene().activeCamera;
  18661. if (this.infiniteDistance && !this.parent && camera) {
  18662. var cameraWorldMatrix = camera.getWorldMatrix();
  18663. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18664. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18665. }
  18666. else {
  18667. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18668. }
  18669. // Composing transformations
  18670. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18671. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18672. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18673. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18674. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18675. // Need to decompose each rotation here
  18676. var currentPosition = BABYLON.Tmp.Vector3[3];
  18677. if (this.parent && this.parent.getWorldMatrix) {
  18678. if (this._transformToBoneReferal) {
  18679. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18680. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18681. }
  18682. else {
  18683. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18684. }
  18685. }
  18686. else {
  18687. currentPosition.copyFrom(this.position);
  18688. }
  18689. currentPosition.subtractInPlace(camera.globalPosition);
  18690. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18691. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18692. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18693. }
  18694. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18695. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18696. }
  18697. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18698. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18699. }
  18700. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18701. }
  18702. else {
  18703. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18704. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18705. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18706. }
  18707. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18708. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18709. }
  18710. // Local world
  18711. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18712. // Parent
  18713. if (this.parent && this.parent.getWorldMatrix) {
  18714. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18715. if (this._transformToBoneReferal) {
  18716. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18717. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18718. }
  18719. else {
  18720. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18721. }
  18722. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18723. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18724. this._worldMatrix.copyFrom(this._localWorld);
  18725. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18726. }
  18727. else {
  18728. if (this._transformToBoneReferal) {
  18729. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18730. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18731. }
  18732. else {
  18733. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18734. }
  18735. }
  18736. this._markSyncedWithParent();
  18737. }
  18738. else {
  18739. this._worldMatrix.copyFrom(this._localWorld);
  18740. }
  18741. // Post multiply inverse of pivotMatrix
  18742. if (this._postMultiplyPivotMatrix) {
  18743. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18744. }
  18745. // Normal matrix
  18746. if (this.scaling.isNonUniform) {
  18747. this._updateNonUniformScalingState(true);
  18748. }
  18749. else if (this.parent && this.parent._nonUniformScaling) {
  18750. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18751. }
  18752. else {
  18753. this._updateNonUniformScalingState(false);
  18754. }
  18755. this._afterComputeWorldMatrix();
  18756. // Absolute position
  18757. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18758. // Callbacks
  18759. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18760. if (!this._poseMatrix) {
  18761. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18762. }
  18763. // Cache the determinant
  18764. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18765. return this._worldMatrix;
  18766. };
  18767. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18768. };
  18769. /**
  18770. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18771. * @param func: callback function to add
  18772. *
  18773. * Returns the TransformNode.
  18774. */
  18775. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18776. this.onAfterWorldMatrixUpdateObservable.add(func);
  18777. return this;
  18778. };
  18779. /**
  18780. * Removes a registered callback function.
  18781. * Returns the TransformNode.
  18782. */
  18783. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  18784. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  18785. return this;
  18786. };
  18787. /**
  18788. * Clone the current transform node
  18789. * Returns the new transform node
  18790. * @param name Name of the new clone
  18791. * @param newParent New parent for the clone
  18792. * @param doNotCloneChildren Do not clone children hierarchy
  18793. */
  18794. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18795. var _this = this;
  18796. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  18797. result.name = name;
  18798. result.id = name;
  18799. if (newParent) {
  18800. result.parent = newParent;
  18801. }
  18802. if (!doNotCloneChildren) {
  18803. // Children
  18804. var directDescendants = this.getDescendants(true);
  18805. for (var index = 0; index < directDescendants.length; index++) {
  18806. var child = directDescendants[index];
  18807. if (child.clone) {
  18808. child.clone(name + "." + child.name, result);
  18809. }
  18810. }
  18811. }
  18812. return result;
  18813. };
  18814. TransformNode.prototype.serialize = function (currentSerializationObject) {
  18815. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  18816. serializationObject.type = this.getClassName();
  18817. // Parent
  18818. if (this.parent) {
  18819. serializationObject.parentId = this.parent.id;
  18820. }
  18821. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  18822. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18823. }
  18824. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  18825. serializationObject.isEnabled = this.isEnabled();
  18826. // Parent
  18827. if (this.parent) {
  18828. serializationObject.parentId = this.parent.id;
  18829. }
  18830. return serializationObject;
  18831. };
  18832. // Statics
  18833. /**
  18834. * Returns a new TransformNode object parsed from the source provided.
  18835. * The parameter `parsedMesh` is the source.
  18836. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18837. */
  18838. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  18839. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  18840. if (BABYLON.Tags) {
  18841. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  18842. }
  18843. if (parsedTransformNode.localMatrix) {
  18844. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  18845. }
  18846. else if (parsedTransformNode.pivotMatrix) {
  18847. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  18848. }
  18849. transformNode.setEnabled(parsedTransformNode.isEnabled);
  18850. // Parent
  18851. if (parsedTransformNode.parentId) {
  18852. transformNode._waitingParentId = parsedTransformNode.parentId;
  18853. }
  18854. return transformNode;
  18855. };
  18856. /**
  18857. * Releases resources associated with this transform node.
  18858. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18859. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18860. */
  18861. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18862. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18863. // Animations
  18864. this.getScene().stopAnimation(this);
  18865. // Remove from scene
  18866. this.getScene().removeTransformNode(this);
  18867. this.onAfterWorldMatrixUpdateObservable.clear();
  18868. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18869. };
  18870. // Statics
  18871. TransformNode.BILLBOARDMODE_NONE = 0;
  18872. TransformNode.BILLBOARDMODE_X = 1;
  18873. TransformNode.BILLBOARDMODE_Y = 2;
  18874. TransformNode.BILLBOARDMODE_Z = 4;
  18875. TransformNode.BILLBOARDMODE_ALL = 7;
  18876. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  18877. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  18878. __decorate([
  18879. BABYLON.serializeAsVector3()
  18880. ], TransformNode.prototype, "_rotation", void 0);
  18881. __decorate([
  18882. BABYLON.serializeAsQuaternion()
  18883. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  18884. __decorate([
  18885. BABYLON.serializeAsVector3()
  18886. ], TransformNode.prototype, "_scaling", void 0);
  18887. __decorate([
  18888. BABYLON.serialize()
  18889. ], TransformNode.prototype, "billboardMode", void 0);
  18890. __decorate([
  18891. BABYLON.serialize()
  18892. ], TransformNode.prototype, "scalingDeterminant", void 0);
  18893. __decorate([
  18894. BABYLON.serialize()
  18895. ], TransformNode.prototype, "infiniteDistance", void 0);
  18896. __decorate([
  18897. BABYLON.serializeAsVector3()
  18898. ], TransformNode.prototype, "position", void 0);
  18899. return TransformNode;
  18900. }(BABYLON.Node));
  18901. BABYLON.TransformNode = TransformNode;
  18902. })(BABYLON || (BABYLON = {}));
  18903. //# sourceMappingURL=babylon.transformNode.js.map
  18904. "use strict";
  18905. var BABYLON;
  18906. (function (BABYLON) {
  18907. var AbstractMesh = /** @class */ (function (_super) {
  18908. __extends(AbstractMesh, _super);
  18909. // Constructor
  18910. function AbstractMesh(name, scene) {
  18911. if (scene === void 0) { scene = null; }
  18912. var _this = _super.call(this, name, scene, false) || this;
  18913. _this._facetNb = 0; // facet number
  18914. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  18915. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  18916. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  18917. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  18918. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  18919. _this._subDiv = {
  18920. max: 1,
  18921. X: 1,
  18922. Y: 1,
  18923. Z: 1
  18924. };
  18925. _this._facetDepthSort = false; // is the facet depth sort to be computed
  18926. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  18927. // Events
  18928. /**
  18929. * An event triggered when this mesh collides with another one
  18930. */
  18931. _this.onCollideObservable = new BABYLON.Observable();
  18932. /**
  18933. * An event triggered when the collision's position changes
  18934. */
  18935. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  18936. /**
  18937. * An event triggered when material is changed
  18938. */
  18939. _this.onMaterialChangedObservable = new BABYLON.Observable();
  18940. // Properties
  18941. _this.definedFacingForward = true; // orientation for POV movement & rotation
  18942. /**
  18943. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  18944. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  18945. * or
  18946. * 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.
  18947. * for more info check WebGl documentations
  18948. */
  18949. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  18950. /**
  18951. * 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:
  18952. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  18953. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  18954. * 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.
  18955. */
  18956. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  18957. /**
  18958. * 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.
  18959. * The default value is -1 which means don't break the query and wait till the result.
  18960. */
  18961. _this.occlusionRetryCount = -1;
  18962. _this._occlusionInternalRetryCounter = 0;
  18963. _this._isOccluded = false;
  18964. _this._isOcclusionQueryInProgress = false;
  18965. _this._visibility = 1.0;
  18966. _this.alphaIndex = Number.MAX_VALUE;
  18967. _this.isVisible = true;
  18968. _this.isPickable = true;
  18969. _this.showBoundingBox = false;
  18970. _this.showSubMeshesBoundingBox = false;
  18971. _this.isBlocker = false;
  18972. _this.enablePointerMoveEvents = false;
  18973. _this.renderingGroupId = 0;
  18974. _this._receiveShadows = false;
  18975. _this.renderOutline = false;
  18976. _this.outlineColor = BABYLON.Color3.Red();
  18977. _this.outlineWidth = 0.02;
  18978. _this.renderOverlay = false;
  18979. _this.overlayColor = BABYLON.Color3.Red();
  18980. _this.overlayAlpha = 0.5;
  18981. _this._hasVertexAlpha = false;
  18982. _this._useVertexColors = true;
  18983. _this._computeBonesUsingShaders = true;
  18984. _this._numBoneInfluencers = 4;
  18985. _this._applyFog = true;
  18986. _this.useOctreeForRenderingSelection = true;
  18987. _this.useOctreeForPicking = true;
  18988. _this.useOctreeForCollisions = true;
  18989. _this._layerMask = 0x0FFFFFFF;
  18990. /**
  18991. * True if the mesh must be rendered in any case.
  18992. */
  18993. _this.alwaysSelectAsActiveMesh = false;
  18994. /**
  18995. * This scene's action manager
  18996. */
  18997. _this.actionManager = null;
  18998. // Physics
  18999. _this.physicsImpostor = null;
  19000. // Collisions
  19001. _this._checkCollisions = false;
  19002. _this._collisionMask = -1;
  19003. _this._collisionGroup = -1;
  19004. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19005. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19006. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19007. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19008. // Edges
  19009. _this.edgesWidth = 1;
  19010. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19011. // Cache
  19012. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19013. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19014. _this._renderId = 0;
  19015. _this._intersectionsInProgress = new Array();
  19016. _this._unIndexed = false;
  19017. _this._lightSources = new Array();
  19018. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19019. if (collidedMesh === void 0) { collidedMesh = null; }
  19020. //TODO move this to the collision coordinator!
  19021. if (_this.getScene().workerCollisions)
  19022. newPosition.multiplyInPlace(_this._collider._radius);
  19023. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19024. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19025. _this.position.addInPlace(_this._diffPositionForCollisions);
  19026. }
  19027. if (collidedMesh) {
  19028. _this.onCollideObservable.notifyObservers(collidedMesh);
  19029. }
  19030. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19031. };
  19032. _this.getScene().addMesh(_this);
  19033. _this._resyncLightSources();
  19034. return _this;
  19035. }
  19036. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19037. get: function () {
  19038. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19039. },
  19040. enumerable: true,
  19041. configurable: true
  19042. });
  19043. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19044. get: function () {
  19045. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19046. },
  19047. enumerable: true,
  19048. configurable: true
  19049. });
  19050. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19051. get: function () {
  19052. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19053. },
  19054. enumerable: true,
  19055. configurable: true
  19056. });
  19057. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19058. get: function () {
  19059. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19060. },
  19061. enumerable: true,
  19062. configurable: true
  19063. });
  19064. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19065. get: function () {
  19066. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19067. },
  19068. enumerable: true,
  19069. configurable: true
  19070. });
  19071. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19072. /**
  19073. * Read-only : the number of facets in the mesh
  19074. */
  19075. get: function () {
  19076. return this._facetNb;
  19077. },
  19078. enumerable: true,
  19079. configurable: true
  19080. });
  19081. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19082. /**
  19083. * The number (integer) of subdivisions per axis in the partioning space
  19084. */
  19085. get: function () {
  19086. return this._partitioningSubdivisions;
  19087. },
  19088. set: function (nb) {
  19089. this._partitioningSubdivisions = nb;
  19090. },
  19091. enumerable: true,
  19092. configurable: true
  19093. });
  19094. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19095. /**
  19096. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19097. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  19098. */
  19099. get: function () {
  19100. return this._partitioningBBoxRatio;
  19101. },
  19102. set: function (ratio) {
  19103. this._partitioningBBoxRatio = ratio;
  19104. },
  19105. enumerable: true,
  19106. configurable: true
  19107. });
  19108. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19109. /**
  19110. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  19111. * Works only for updatable meshes.
  19112. * Doesn't work with multi-materials.
  19113. */
  19114. get: function () {
  19115. return this._facetDepthSort;
  19116. },
  19117. set: function (sort) {
  19118. this._facetDepthSort = sort;
  19119. },
  19120. enumerable: true,
  19121. configurable: true
  19122. });
  19123. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19124. /**
  19125. * The location (Vector3) where the facet depth sort must be computed from.
  19126. * By default, the active camera position.
  19127. * Used only when facet depth sort is enabled.
  19128. */
  19129. get: function () {
  19130. return this._facetDepthSortFrom;
  19131. },
  19132. set: function (location) {
  19133. this._facetDepthSortFrom = location;
  19134. },
  19135. enumerable: true,
  19136. configurable: true
  19137. });
  19138. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19139. /**
  19140. * Read-only boolean : is the feature facetData enabled ?
  19141. */
  19142. get: function () {
  19143. return this._facetDataEnabled;
  19144. },
  19145. enumerable: true,
  19146. configurable: true
  19147. });
  19148. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19149. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19150. return false;
  19151. }
  19152. this._markSubMeshesAsMiscDirty();
  19153. return true;
  19154. };
  19155. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19156. set: function (callback) {
  19157. if (this._onCollideObserver) {
  19158. this.onCollideObservable.remove(this._onCollideObserver);
  19159. }
  19160. this._onCollideObserver = this.onCollideObservable.add(callback);
  19161. },
  19162. enumerable: true,
  19163. configurable: true
  19164. });
  19165. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19166. set: function (callback) {
  19167. if (this._onCollisionPositionChangeObserver) {
  19168. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19169. }
  19170. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19171. },
  19172. enumerable: true,
  19173. configurable: true
  19174. });
  19175. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19176. /**
  19177. * Property isOccluded : 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.
  19178. */
  19179. get: function () {
  19180. return this._isOccluded;
  19181. },
  19182. set: function (value) {
  19183. this._isOccluded = value;
  19184. },
  19185. enumerable: true,
  19186. configurable: true
  19187. });
  19188. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19189. /**
  19190. * Flag to check the progress status of the query
  19191. */
  19192. get: function () {
  19193. return this._isOcclusionQueryInProgress;
  19194. },
  19195. enumerable: true,
  19196. configurable: true
  19197. });
  19198. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19199. /**
  19200. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19201. */
  19202. get: function () {
  19203. return this._visibility;
  19204. },
  19205. /**
  19206. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19207. */
  19208. set: function (value) {
  19209. if (this._visibility === value) {
  19210. return;
  19211. }
  19212. this._visibility = value;
  19213. this._markSubMeshesAsMiscDirty();
  19214. },
  19215. enumerable: true,
  19216. configurable: true
  19217. });
  19218. Object.defineProperty(AbstractMesh.prototype, "material", {
  19219. get: function () {
  19220. return this._material;
  19221. },
  19222. set: function (value) {
  19223. if (this._material === value) {
  19224. return;
  19225. }
  19226. this._material = value;
  19227. if (this.onMaterialChangedObservable.hasObservers) {
  19228. this.onMaterialChangedObservable.notifyObservers(this);
  19229. }
  19230. if (!this.subMeshes) {
  19231. return;
  19232. }
  19233. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19234. var subMesh = _a[_i];
  19235. subMesh.setEffect(null);
  19236. }
  19237. },
  19238. enumerable: true,
  19239. configurable: true
  19240. });
  19241. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19242. get: function () {
  19243. return this._receiveShadows;
  19244. },
  19245. set: function (value) {
  19246. if (this._receiveShadows === value) {
  19247. return;
  19248. }
  19249. this._receiveShadows = value;
  19250. this._markSubMeshesAsLightDirty();
  19251. },
  19252. enumerable: true,
  19253. configurable: true
  19254. });
  19255. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19256. get: function () {
  19257. return this._hasVertexAlpha;
  19258. },
  19259. set: function (value) {
  19260. if (this._hasVertexAlpha === value) {
  19261. return;
  19262. }
  19263. this._hasVertexAlpha = value;
  19264. this._markSubMeshesAsAttributesDirty();
  19265. this._markSubMeshesAsMiscDirty();
  19266. },
  19267. enumerable: true,
  19268. configurable: true
  19269. });
  19270. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19271. get: function () {
  19272. return this._useVertexColors;
  19273. },
  19274. set: function (value) {
  19275. if (this._useVertexColors === value) {
  19276. return;
  19277. }
  19278. this._useVertexColors = value;
  19279. this._markSubMeshesAsAttributesDirty();
  19280. },
  19281. enumerable: true,
  19282. configurable: true
  19283. });
  19284. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19285. get: function () {
  19286. return this._computeBonesUsingShaders;
  19287. },
  19288. set: function (value) {
  19289. if (this._computeBonesUsingShaders === value) {
  19290. return;
  19291. }
  19292. this._computeBonesUsingShaders = value;
  19293. this._markSubMeshesAsAttributesDirty();
  19294. },
  19295. enumerable: true,
  19296. configurable: true
  19297. });
  19298. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19299. get: function () {
  19300. return this._numBoneInfluencers;
  19301. },
  19302. set: function (value) {
  19303. if (this._numBoneInfluencers === value) {
  19304. return;
  19305. }
  19306. this._numBoneInfluencers = value;
  19307. this._markSubMeshesAsAttributesDirty();
  19308. },
  19309. enumerable: true,
  19310. configurable: true
  19311. });
  19312. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19313. get: function () {
  19314. return this._applyFog;
  19315. },
  19316. set: function (value) {
  19317. if (this._applyFog === value) {
  19318. return;
  19319. }
  19320. this._applyFog = value;
  19321. this._markSubMeshesAsMiscDirty();
  19322. },
  19323. enumerable: true,
  19324. configurable: true
  19325. });
  19326. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19327. get: function () {
  19328. return this._layerMask;
  19329. },
  19330. set: function (value) {
  19331. if (value === this._layerMask) {
  19332. return;
  19333. }
  19334. this._layerMask = value;
  19335. this._resyncLightSources();
  19336. },
  19337. enumerable: true,
  19338. configurable: true
  19339. });
  19340. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19341. get: function () {
  19342. return this._collisionMask;
  19343. },
  19344. set: function (mask) {
  19345. this._collisionMask = !isNaN(mask) ? mask : -1;
  19346. },
  19347. enumerable: true,
  19348. configurable: true
  19349. });
  19350. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19351. get: function () {
  19352. return this._collisionGroup;
  19353. },
  19354. set: function (mask) {
  19355. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19356. },
  19357. enumerable: true,
  19358. configurable: true
  19359. });
  19360. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19361. get: function () {
  19362. return null;
  19363. },
  19364. enumerable: true,
  19365. configurable: true
  19366. });
  19367. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19368. get: function () {
  19369. return this._skeleton;
  19370. },
  19371. set: function (value) {
  19372. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19373. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19374. }
  19375. if (value && value.needInitialSkinMatrix) {
  19376. value._registerMeshWithPoseMatrix(this);
  19377. }
  19378. this._skeleton = value;
  19379. if (!this._skeleton) {
  19380. this._bonesTransformMatrices = null;
  19381. }
  19382. this._markSubMeshesAsAttributesDirty();
  19383. },
  19384. enumerable: true,
  19385. configurable: true
  19386. });
  19387. /**
  19388. * Returns the string "AbstractMesh"
  19389. */
  19390. AbstractMesh.prototype.getClassName = function () {
  19391. return "AbstractMesh";
  19392. };
  19393. /**
  19394. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19395. */
  19396. AbstractMesh.prototype.toString = function (fullDetails) {
  19397. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19398. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19399. if (this._skeleton) {
  19400. ret += ", skeleton: " + this._skeleton.name;
  19401. }
  19402. if (fullDetails) {
  19403. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19404. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19405. }
  19406. return ret;
  19407. };
  19408. AbstractMesh.prototype._rebuild = function () {
  19409. if (this._occlusionQuery) {
  19410. this._occlusionQuery = null;
  19411. }
  19412. if (this._edgesRenderer) {
  19413. this._edgesRenderer._rebuild();
  19414. }
  19415. if (!this.subMeshes) {
  19416. return;
  19417. }
  19418. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19419. var subMesh = _a[_i];
  19420. subMesh._rebuild();
  19421. }
  19422. };
  19423. AbstractMesh.prototype._resyncLightSources = function () {
  19424. this._lightSources.length = 0;
  19425. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19426. var light = _a[_i];
  19427. if (!light.isEnabled()) {
  19428. continue;
  19429. }
  19430. if (light.canAffectMesh(this)) {
  19431. this._lightSources.push(light);
  19432. }
  19433. }
  19434. this._markSubMeshesAsLightDirty();
  19435. };
  19436. AbstractMesh.prototype._resyncLighSource = function (light) {
  19437. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19438. var index = this._lightSources.indexOf(light);
  19439. if (index === -1) {
  19440. if (!isIn) {
  19441. return;
  19442. }
  19443. this._lightSources.push(light);
  19444. }
  19445. else {
  19446. if (isIn) {
  19447. return;
  19448. }
  19449. this._lightSources.splice(index, 1);
  19450. }
  19451. this._markSubMeshesAsLightDirty();
  19452. };
  19453. AbstractMesh.prototype._removeLightSource = function (light) {
  19454. var index = this._lightSources.indexOf(light);
  19455. if (index === -1) {
  19456. return;
  19457. }
  19458. this._lightSources.splice(index, 1);
  19459. this._markSubMeshesAsLightDirty();
  19460. };
  19461. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19462. if (!this.subMeshes) {
  19463. return;
  19464. }
  19465. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19466. var subMesh = _a[_i];
  19467. if (subMesh._materialDefines) {
  19468. func(subMesh._materialDefines);
  19469. }
  19470. }
  19471. };
  19472. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19473. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19474. };
  19475. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19476. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19477. };
  19478. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19479. if (!this.subMeshes) {
  19480. return;
  19481. }
  19482. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19483. var subMesh = _a[_i];
  19484. var material = subMesh.getMaterial();
  19485. if (material) {
  19486. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19487. }
  19488. }
  19489. };
  19490. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19491. /**
  19492. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19493. * Default : (1.0, 1.0, 1.0)
  19494. */
  19495. get: function () {
  19496. return this._scaling;
  19497. },
  19498. /**
  19499. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19500. * Default : (1.0, 1.0, 1.0)
  19501. */
  19502. set: function (newScaling) {
  19503. this._scaling = newScaling;
  19504. if (this.physicsImpostor) {
  19505. this.physicsImpostor.forceUpdate();
  19506. }
  19507. },
  19508. enumerable: true,
  19509. configurable: true
  19510. });
  19511. // Methods
  19512. /**
  19513. * Disables the mesh edger rendering mode.
  19514. * Returns the AbstractMesh.
  19515. */
  19516. AbstractMesh.prototype.disableEdgesRendering = function () {
  19517. if (this._edgesRenderer) {
  19518. this._edgesRenderer.dispose();
  19519. this._edgesRenderer = null;
  19520. }
  19521. return this;
  19522. };
  19523. /**
  19524. * Enables the edge rendering mode on the mesh.
  19525. * This mode makes the mesh edges visible.
  19526. * Returns the AbstractMesh.
  19527. */
  19528. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19529. if (epsilon === void 0) { epsilon = 0.95; }
  19530. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19531. this.disableEdgesRendering();
  19532. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19533. return this;
  19534. };
  19535. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19536. /**
  19537. * Returns true if the mesh is blocked. Used by the class Mesh.
  19538. * Returns the boolean `false` by default.
  19539. */
  19540. get: function () {
  19541. return false;
  19542. },
  19543. enumerable: true,
  19544. configurable: true
  19545. });
  19546. /**
  19547. * Returns the mesh itself by default, used by the class Mesh.
  19548. * Returned type : AbstractMesh
  19549. */
  19550. AbstractMesh.prototype.getLOD = function (camera) {
  19551. return this;
  19552. };
  19553. /**
  19554. * Returns 0 by default, used by the class Mesh.
  19555. * Returns an integer.
  19556. */
  19557. AbstractMesh.prototype.getTotalVertices = function () {
  19558. return 0;
  19559. };
  19560. /**
  19561. * Returns null by default, used by the class Mesh.
  19562. * Returned type : integer array
  19563. */
  19564. AbstractMesh.prototype.getIndices = function () {
  19565. return null;
  19566. };
  19567. /**
  19568. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  19569. * Returned type : float array or Float32Array
  19570. */
  19571. AbstractMesh.prototype.getVerticesData = function (kind) {
  19572. return null;
  19573. };
  19574. /**
  19575. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19576. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19577. * The `data` are either a numeric array either a Float32Array.
  19578. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19579. * 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).
  19580. * Note that a new underlying VertexBuffer object is created each call.
  19581. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19582. *
  19583. * Possible `kind` values :
  19584. * - BABYLON.VertexBuffer.PositionKind
  19585. * - BABYLON.VertexBuffer.UVKind
  19586. * - BABYLON.VertexBuffer.UV2Kind
  19587. * - BABYLON.VertexBuffer.UV3Kind
  19588. * - BABYLON.VertexBuffer.UV4Kind
  19589. * - BABYLON.VertexBuffer.UV5Kind
  19590. * - BABYLON.VertexBuffer.UV6Kind
  19591. * - BABYLON.VertexBuffer.ColorKind
  19592. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19593. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19594. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19595. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19596. *
  19597. * Returns the Mesh.
  19598. */
  19599. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19600. return this;
  19601. };
  19602. /**
  19603. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19604. * If the mesh has no geometry, it is simply returned as it is.
  19605. * The `data` are either a numeric array either a Float32Array.
  19606. * No new underlying VertexBuffer object is created.
  19607. * 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.
  19608. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19609. *
  19610. * Possible `kind` values :
  19611. * - BABYLON.VertexBuffer.PositionKind
  19612. * - BABYLON.VertexBuffer.UVKind
  19613. * - BABYLON.VertexBuffer.UV2Kind
  19614. * - BABYLON.VertexBuffer.UV3Kind
  19615. * - BABYLON.VertexBuffer.UV4Kind
  19616. * - BABYLON.VertexBuffer.UV5Kind
  19617. * - BABYLON.VertexBuffer.UV6Kind
  19618. * - BABYLON.VertexBuffer.ColorKind
  19619. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19620. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19621. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19622. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19623. *
  19624. * Returns the Mesh.
  19625. */
  19626. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19627. return this;
  19628. };
  19629. /**
  19630. * Sets the mesh indices.
  19631. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19632. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19633. * This method creates a new index buffer each call.
  19634. * Returns the Mesh.
  19635. */
  19636. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19637. return this;
  19638. };
  19639. /** Returns false by default, used by the class Mesh.
  19640. * Returns a boolean
  19641. */
  19642. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19643. return false;
  19644. };
  19645. /**
  19646. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  19647. * Returns a BoundingInfo
  19648. */
  19649. AbstractMesh.prototype.getBoundingInfo = function () {
  19650. if (this._masterMesh) {
  19651. return this._masterMesh.getBoundingInfo();
  19652. }
  19653. if (!this._boundingInfo) {
  19654. // this._boundingInfo is being created here
  19655. this._updateBoundingInfo();
  19656. }
  19657. // cannot be null.
  19658. return this._boundingInfo;
  19659. };
  19660. /**
  19661. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  19662. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  19663. */
  19664. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19665. if (includeDescendants === void 0) { includeDescendants = true; }
  19666. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19667. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19668. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19669. if (maxDimension === 0) {
  19670. return this;
  19671. }
  19672. var scale = 1 / maxDimension;
  19673. this.scaling.scaleInPlace(scale);
  19674. return this;
  19675. };
  19676. /**
  19677. * Sets a mesh new object BoundingInfo.
  19678. * Returns the AbstractMesh.
  19679. */
  19680. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19681. this._boundingInfo = boundingInfo;
  19682. return this;
  19683. };
  19684. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19685. get: function () {
  19686. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19687. },
  19688. enumerable: true,
  19689. configurable: true
  19690. });
  19691. AbstractMesh.prototype._preActivate = function () {
  19692. };
  19693. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19694. };
  19695. AbstractMesh.prototype._activate = function (renderId) {
  19696. this._renderId = renderId;
  19697. };
  19698. /**
  19699. * Returns the latest update of the World matrix
  19700. * Returns a Matrix.
  19701. */
  19702. AbstractMesh.prototype.getWorldMatrix = function () {
  19703. if (this._masterMesh) {
  19704. return this._masterMesh.getWorldMatrix();
  19705. }
  19706. return _super.prototype.getWorldMatrix.call(this);
  19707. };
  19708. /**
  19709. * Returns the latest update of the World matrix determinant.
  19710. */
  19711. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19712. if (this._masterMesh) {
  19713. return this._masterMesh._getWorldMatrixDeterminant();
  19714. }
  19715. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19716. };
  19717. // ================================== Point of View Movement =================================
  19718. /**
  19719. * Perform relative position change from the point of view of behind the front of the mesh.
  19720. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19721. * Supports definition of mesh facing forward or backward.
  19722. * @param {number} amountRight
  19723. * @param {number} amountUp
  19724. * @param {number} amountForward
  19725. *
  19726. * Returns the AbstractMesh.
  19727. */
  19728. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19729. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19730. return this;
  19731. };
  19732. /**
  19733. * Calculate relative position change from the point of view of behind the front of the mesh.
  19734. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19735. * Supports definition of mesh facing forward or backward.
  19736. * @param {number} amountRight
  19737. * @param {number} amountUp
  19738. * @param {number} amountForward
  19739. *
  19740. * Returns a new Vector3.
  19741. */
  19742. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19743. var rotMatrix = new BABYLON.Matrix();
  19744. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19745. rotQuaternion.toRotationMatrix(rotMatrix);
  19746. var translationDelta = BABYLON.Vector3.Zero();
  19747. var defForwardMult = this.definedFacingForward ? -1 : 1;
  19748. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  19749. return translationDelta;
  19750. };
  19751. // ================================== Point of View Rotation =================================
  19752. /**
  19753. * Perform relative rotation change from the point of view of behind the front of the mesh.
  19754. * Supports definition of mesh facing forward or backward.
  19755. * @param {number} flipBack
  19756. * @param {number} twirlClockwise
  19757. * @param {number} tiltRight
  19758. *
  19759. * Returns the AbstractMesh.
  19760. */
  19761. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19762. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  19763. return this;
  19764. };
  19765. /**
  19766. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  19767. * Supports definition of mesh facing forward or backward.
  19768. * @param {number} flipBack
  19769. * @param {number} twirlClockwise
  19770. * @param {number} tiltRight
  19771. *
  19772. * Returns a new Vector3.
  19773. */
  19774. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19775. var defForwardMult = this.definedFacingForward ? 1 : -1;
  19776. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  19777. };
  19778. /**
  19779. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  19780. * @param includeDescendants Include bounding info from descendants as well (true by default).
  19781. */
  19782. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  19783. if (includeDescendants === void 0) { includeDescendants = true; }
  19784. this.computeWorldMatrix(true);
  19785. var min;
  19786. var max;
  19787. var boundingInfo = this.getBoundingInfo();
  19788. if (!this.subMeshes) {
  19789. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19790. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19791. }
  19792. else {
  19793. min = boundingInfo.boundingBox.minimumWorld;
  19794. max = boundingInfo.boundingBox.maximumWorld;
  19795. }
  19796. if (includeDescendants) {
  19797. var descendants = this.getDescendants(false);
  19798. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  19799. var descendant = descendants_1[_i];
  19800. var childMesh = descendant;
  19801. childMesh.computeWorldMatrix(true);
  19802. //make sure we have the needed params to get mix and max
  19803. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  19804. continue;
  19805. }
  19806. var childBoundingInfo = childMesh.getBoundingInfo();
  19807. var boundingBox = childBoundingInfo.boundingBox;
  19808. var minBox = boundingBox.minimumWorld;
  19809. var maxBox = boundingBox.maximumWorld;
  19810. BABYLON.Tools.CheckExtends(minBox, min, max);
  19811. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19812. }
  19813. }
  19814. return {
  19815. min: min,
  19816. max: max
  19817. };
  19818. };
  19819. /**
  19820. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  19821. * Returns the AbstractMesh.
  19822. */
  19823. AbstractMesh.prototype._updateBoundingInfo = function () {
  19824. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  19825. this._boundingInfo.update(this.worldMatrixFromCache);
  19826. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19827. return this;
  19828. };
  19829. /**
  19830. * Update a mesh's children BoundingInfo objects only.
  19831. * Returns the AbstractMesh.
  19832. */
  19833. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  19834. if (!this.subMeshes) {
  19835. return this;
  19836. }
  19837. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  19838. var subMesh = this.subMeshes[subIndex];
  19839. if (!subMesh.IsGlobal) {
  19840. subMesh.updateBoundingInfo(matrix);
  19841. }
  19842. }
  19843. return this;
  19844. };
  19845. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  19846. // Bounding info
  19847. this._updateBoundingInfo();
  19848. };
  19849. /**
  19850. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  19851. * A mesh is in the frustum if its bounding box intersects the frustum.
  19852. * Boolean returned.
  19853. */
  19854. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  19855. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  19856. };
  19857. /**
  19858. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  19859. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  19860. * Boolean returned.
  19861. */
  19862. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19863. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  19864. ;
  19865. };
  19866. /**
  19867. * True if the mesh intersects another mesh or a SolidParticle object.
  19868. * 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)
  19869. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  19870. * Returns a boolean.
  19871. */
  19872. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  19873. if (precise === void 0) { precise = false; }
  19874. if (!this._boundingInfo || !mesh._boundingInfo) {
  19875. return false;
  19876. }
  19877. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  19878. return true;
  19879. }
  19880. if (includeDescendants) {
  19881. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  19882. var child = _a[_i];
  19883. if (child.intersectsMesh(mesh, precise, true)) {
  19884. return true;
  19885. }
  19886. }
  19887. }
  19888. return false;
  19889. };
  19890. /**
  19891. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  19892. * Returns a boolean.
  19893. */
  19894. AbstractMesh.prototype.intersectsPoint = function (point) {
  19895. if (!this._boundingInfo) {
  19896. return false;
  19897. }
  19898. return this._boundingInfo.intersectsPoint(point);
  19899. };
  19900. AbstractMesh.prototype.getPhysicsImpostor = function () {
  19901. return this.physicsImpostor;
  19902. };
  19903. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  19904. if (camera === void 0) { camera = null; }
  19905. if (!camera) {
  19906. camera = this.getScene().activeCamera;
  19907. }
  19908. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  19909. };
  19910. /**
  19911. * Returns the distance from the mesh to the active camera.
  19912. * Returns a float.
  19913. */
  19914. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  19915. if (camera === void 0) { camera = null; }
  19916. if (!camera) {
  19917. camera = this.getScene().activeCamera;
  19918. }
  19919. return this.absolutePosition.subtract(camera.position).length();
  19920. };
  19921. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  19922. if (!this.physicsImpostor) {
  19923. return this;
  19924. }
  19925. this.physicsImpostor.applyImpulse(force, contactPoint);
  19926. return this;
  19927. };
  19928. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  19929. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  19930. return this;
  19931. }
  19932. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  19933. mainPivot: pivot1,
  19934. connectedPivot: pivot2,
  19935. nativeParams: options
  19936. });
  19937. return this;
  19938. };
  19939. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  19940. // Collisions
  19941. /**
  19942. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  19943. * Default `false`.
  19944. */
  19945. get: function () {
  19946. return this._checkCollisions;
  19947. },
  19948. set: function (collisionEnabled) {
  19949. this._checkCollisions = collisionEnabled;
  19950. if (this.getScene().workerCollisions) {
  19951. this.getScene().collisionCoordinator.onMeshUpdated(this);
  19952. }
  19953. },
  19954. enumerable: true,
  19955. configurable: true
  19956. });
  19957. Object.defineProperty(AbstractMesh.prototype, "collider", {
  19958. /**
  19959. * Gets Collider object used to compute collisions (not physics)
  19960. */
  19961. get: function () {
  19962. return this._collider;
  19963. },
  19964. enumerable: true,
  19965. configurable: true
  19966. });
  19967. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  19968. var globalPosition = this.getAbsolutePosition();
  19969. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  19970. if (!this._collider) {
  19971. this._collider = new BABYLON.Collider();
  19972. }
  19973. this._collider._radius = this.ellipsoid;
  19974. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  19975. return this;
  19976. };
  19977. // Submeshes octree
  19978. /**
  19979. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  19980. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  19981. * Returns an Octree of submeshes.
  19982. */
  19983. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  19984. if (maxCapacity === void 0) { maxCapacity = 64; }
  19985. if (maxDepth === void 0) { maxDepth = 2; }
  19986. if (!this._submeshesOctree) {
  19987. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  19988. }
  19989. this.computeWorldMatrix(true);
  19990. var boundingInfo = this.getBoundingInfo();
  19991. // Update octree
  19992. var bbox = boundingInfo.boundingBox;
  19993. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  19994. return this._submeshesOctree;
  19995. };
  19996. // Collisions
  19997. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  19998. this._generatePointsArray();
  19999. if (!this._positions) {
  20000. return this;
  20001. }
  20002. // Transformation
  20003. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20004. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20005. subMesh._lastColliderWorldVertices = [];
  20006. subMesh._trianglePlanes = [];
  20007. var start = subMesh.verticesStart;
  20008. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20009. for (var i = start; i < end; i++) {
  20010. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20011. }
  20012. }
  20013. // Collide
  20014. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20015. if (collider.collisionFound) {
  20016. collider.collidedMesh = this;
  20017. }
  20018. return this;
  20019. };
  20020. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20021. var subMeshes;
  20022. var len;
  20023. // Octrees
  20024. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20025. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20026. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20027. len = intersections.length;
  20028. subMeshes = intersections.data;
  20029. }
  20030. else {
  20031. subMeshes = this.subMeshes;
  20032. len = subMeshes.length;
  20033. }
  20034. for (var index = 0; index < len; index++) {
  20035. var subMesh = subMeshes[index];
  20036. // Bounding test
  20037. if (len > 1 && !subMesh._checkCollision(collider))
  20038. continue;
  20039. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20040. }
  20041. return this;
  20042. };
  20043. AbstractMesh.prototype._checkCollision = function (collider) {
  20044. // Bounding box test
  20045. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20046. return this;
  20047. // Transformation matrix
  20048. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20049. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20050. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20051. return this;
  20052. };
  20053. // Picking
  20054. AbstractMesh.prototype._generatePointsArray = function () {
  20055. return false;
  20056. };
  20057. /**
  20058. * Checks if the passed Ray intersects with the mesh.
  20059. * Returns an object PickingInfo.
  20060. */
  20061. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20062. var pickingInfo = new BABYLON.PickingInfo();
  20063. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20064. return pickingInfo;
  20065. }
  20066. if (!this._generatePointsArray()) {
  20067. return pickingInfo;
  20068. }
  20069. var intersectInfo = null;
  20070. // Octrees
  20071. var subMeshes;
  20072. var len;
  20073. if (this._submeshesOctree && this.useOctreeForPicking) {
  20074. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20075. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20076. len = intersections.length;
  20077. subMeshes = intersections.data;
  20078. }
  20079. else {
  20080. subMeshes = this.subMeshes;
  20081. len = subMeshes.length;
  20082. }
  20083. for (var index = 0; index < len; index++) {
  20084. var subMesh = subMeshes[index];
  20085. // Bounding test
  20086. if (len > 1 && !subMesh.canIntersects(ray))
  20087. continue;
  20088. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20089. if (currentIntersectInfo) {
  20090. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20091. intersectInfo = currentIntersectInfo;
  20092. intersectInfo.subMeshId = index;
  20093. if (fastCheck) {
  20094. break;
  20095. }
  20096. }
  20097. }
  20098. }
  20099. if (intersectInfo) {
  20100. // Get picked point
  20101. var world = this.getWorldMatrix();
  20102. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20103. var direction = ray.direction.clone();
  20104. direction = direction.scale(intersectInfo.distance);
  20105. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20106. var pickedPoint = worldOrigin.add(worldDirection);
  20107. // Return result
  20108. pickingInfo.hit = true;
  20109. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20110. pickingInfo.pickedPoint = pickedPoint;
  20111. pickingInfo.pickedMesh = this;
  20112. pickingInfo.bu = intersectInfo.bu || 0;
  20113. pickingInfo.bv = intersectInfo.bv || 0;
  20114. pickingInfo.faceId = intersectInfo.faceId;
  20115. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20116. return pickingInfo;
  20117. }
  20118. return pickingInfo;
  20119. };
  20120. /**
  20121. * Clones the mesh, used by the class Mesh.
  20122. * Just returns `null` for an AbstractMesh.
  20123. */
  20124. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20125. return null;
  20126. };
  20127. /**
  20128. * Disposes all the mesh submeshes.
  20129. * Returns the AbstractMesh.
  20130. */
  20131. AbstractMesh.prototype.releaseSubMeshes = function () {
  20132. if (this.subMeshes) {
  20133. while (this.subMeshes.length) {
  20134. this.subMeshes[0].dispose();
  20135. }
  20136. }
  20137. else {
  20138. this.subMeshes = new Array();
  20139. }
  20140. return this;
  20141. };
  20142. /**
  20143. * Releases resources associated with this abstract mesh.
  20144. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20145. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20146. */
  20147. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20148. var _this = this;
  20149. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20150. var index;
  20151. // Smart Array Retainers.
  20152. this.getScene().freeActiveMeshes();
  20153. this.getScene().freeRenderingGroups();
  20154. // Action manager
  20155. if (this.actionManager !== undefined && this.actionManager !== null) {
  20156. this.actionManager.dispose();
  20157. this.actionManager = null;
  20158. }
  20159. // Skeleton
  20160. this._skeleton = null;
  20161. // Physics
  20162. if (this.physicsImpostor) {
  20163. this.physicsImpostor.dispose();
  20164. }
  20165. // Intersections in progress
  20166. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20167. var other = this._intersectionsInProgress[index];
  20168. var pos = other._intersectionsInProgress.indexOf(this);
  20169. other._intersectionsInProgress.splice(pos, 1);
  20170. }
  20171. this._intersectionsInProgress = [];
  20172. // Lights
  20173. var lights = this.getScene().lights;
  20174. lights.forEach(function (light) {
  20175. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20176. if (meshIndex !== -1) {
  20177. light.includedOnlyMeshes.splice(meshIndex, 1);
  20178. }
  20179. meshIndex = light.excludedMeshes.indexOf(_this);
  20180. if (meshIndex !== -1) {
  20181. light.excludedMeshes.splice(meshIndex, 1);
  20182. }
  20183. // Shadow generators
  20184. var generator = light.getShadowGenerator();
  20185. if (generator) {
  20186. var shadowMap = generator.getShadowMap();
  20187. if (shadowMap && shadowMap.renderList) {
  20188. meshIndex = shadowMap.renderList.indexOf(_this);
  20189. if (meshIndex !== -1) {
  20190. shadowMap.renderList.splice(meshIndex, 1);
  20191. }
  20192. }
  20193. }
  20194. });
  20195. // Edges
  20196. if (this._edgesRenderer) {
  20197. this._edgesRenderer.dispose();
  20198. this._edgesRenderer = null;
  20199. }
  20200. // SubMeshes
  20201. if (this.getClassName() !== "InstancedMesh") {
  20202. this.releaseSubMeshes();
  20203. }
  20204. // Octree
  20205. var sceneOctree = this.getScene().selectionOctree;
  20206. if (sceneOctree !== undefined && sceneOctree !== null) {
  20207. var index = sceneOctree.dynamicContent.indexOf(this);
  20208. if (index !== -1) {
  20209. sceneOctree.dynamicContent.splice(index, 1);
  20210. }
  20211. }
  20212. // Query
  20213. var engine = this.getScene().getEngine();
  20214. if (this._occlusionQuery) {
  20215. this._isOcclusionQueryInProgress = false;
  20216. engine.deleteQuery(this._occlusionQuery);
  20217. this._occlusionQuery = null;
  20218. }
  20219. // Engine
  20220. engine.wipeCaches();
  20221. // Remove from scene
  20222. this.getScene().removeMesh(this);
  20223. if (disposeMaterialAndTextures) {
  20224. if (this.material) {
  20225. this.material.dispose(false, true);
  20226. }
  20227. }
  20228. if (!doNotRecurse) {
  20229. // Particles
  20230. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20231. if (this.getScene().particleSystems[index].emitter === this) {
  20232. this.getScene().particleSystems[index].dispose();
  20233. index--;
  20234. }
  20235. }
  20236. }
  20237. // facet data
  20238. if (this._facetDataEnabled) {
  20239. this.disableFacetData();
  20240. }
  20241. this.onAfterWorldMatrixUpdateObservable.clear();
  20242. this.onCollideObservable.clear();
  20243. this.onCollisionPositionChangeObservable.clear();
  20244. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20245. };
  20246. /**
  20247. * Adds the passed mesh as a child to the current mesh.
  20248. * Returns the AbstractMesh.
  20249. */
  20250. AbstractMesh.prototype.addChild = function (mesh) {
  20251. mesh.setParent(this);
  20252. return this;
  20253. };
  20254. /**
  20255. * Removes the passed mesh from the current mesh children list.
  20256. * Returns the AbstractMesh.
  20257. */
  20258. AbstractMesh.prototype.removeChild = function (mesh) {
  20259. mesh.setParent(null);
  20260. return this;
  20261. };
  20262. // Facet data
  20263. /**
  20264. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  20265. * Returns the AbstractMesh.
  20266. */
  20267. AbstractMesh.prototype._initFacetData = function () {
  20268. if (!this._facetNormals) {
  20269. this._facetNormals = new Array();
  20270. }
  20271. if (!this._facetPositions) {
  20272. this._facetPositions = new Array();
  20273. }
  20274. if (!this._facetPartitioning) {
  20275. this._facetPartitioning = new Array();
  20276. }
  20277. this._facetNb = (this.getIndices().length / 3) | 0;
  20278. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20279. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20280. for (var f = 0; f < this._facetNb; f++) {
  20281. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20282. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20283. }
  20284. this._facetDataEnabled = true;
  20285. return this;
  20286. };
  20287. /**
  20288. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20289. * This method can be called within the render loop.
  20290. * 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.
  20291. * Returns the AbstractMesh.
  20292. */
  20293. AbstractMesh.prototype.updateFacetData = function () {
  20294. if (!this._facetDataEnabled) {
  20295. this._initFacetData();
  20296. }
  20297. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20298. var indices = this.getIndices();
  20299. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20300. var bInfo = this.getBoundingInfo();
  20301. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20302. // init arrays, matrix and sort function on first call
  20303. this._facetDepthSortEnabled = true;
  20304. if (indices instanceof Uint16Array) {
  20305. this._depthSortedIndices = new Uint16Array(indices);
  20306. }
  20307. else if (indices instanceof Uint32Array) {
  20308. this._depthSortedIndices = new Uint32Array(indices);
  20309. }
  20310. else {
  20311. var needs32bits = false;
  20312. for (var i = 0; i < indices.length; i++) {
  20313. if (indices[i] > 65535) {
  20314. needs32bits = true;
  20315. break;
  20316. }
  20317. }
  20318. if (needs32bits) {
  20319. this._depthSortedIndices = new Uint32Array(indices);
  20320. }
  20321. else {
  20322. this._depthSortedIndices = new Uint16Array(indices);
  20323. }
  20324. }
  20325. this._facetDepthSortFunction = function (f1, f2) {
  20326. return (f2.sqDistance - f1.sqDistance);
  20327. };
  20328. if (!this._facetDepthSortFrom) {
  20329. var camera = this.getScene().activeCamera;
  20330. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20331. }
  20332. this._depthSortedFacets = [];
  20333. for (var f = 0; f < this._facetNb; f++) {
  20334. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20335. this._depthSortedFacets.push(depthSortedFacet);
  20336. }
  20337. this._invertedMatrix = BABYLON.Matrix.Identity();
  20338. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20339. }
  20340. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20341. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20342. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20343. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20344. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20345. this._subDiv.max = this._partitioningSubdivisions;
  20346. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20347. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20348. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20349. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20350. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20351. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20352. // set the parameters for ComputeNormals()
  20353. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20354. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20355. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20356. this._facetParameters.bInfo = bInfo;
  20357. this._facetParameters.bbSize = this._bbSize;
  20358. this._facetParameters.subDiv = this._subDiv;
  20359. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20360. this._facetParameters.depthSort = this._facetDepthSort;
  20361. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20362. this.computeWorldMatrix(true);
  20363. this._worldMatrix.invertToRef(this._invertedMatrix);
  20364. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20365. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20366. }
  20367. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20368. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20369. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20370. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20371. var l = (this._depthSortedIndices.length / 3) | 0;
  20372. for (var f = 0; f < l; f++) {
  20373. var sind = this._depthSortedFacets[f].ind;
  20374. this._depthSortedIndices[f * 3] = indices[sind];
  20375. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20376. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20377. }
  20378. this.updateIndices(this._depthSortedIndices);
  20379. }
  20380. return this;
  20381. };
  20382. /**
  20383. * Returns the facetLocalNormals array.
  20384. * The normals are expressed in the mesh local space.
  20385. */
  20386. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20387. if (!this._facetNormals) {
  20388. this.updateFacetData();
  20389. }
  20390. return this._facetNormals;
  20391. };
  20392. /**
  20393. * Returns the facetLocalPositions array.
  20394. * The facet positions are expressed in the mesh local space.
  20395. */
  20396. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20397. if (!this._facetPositions) {
  20398. this.updateFacetData();
  20399. }
  20400. return this._facetPositions;
  20401. };
  20402. /**
  20403. * Returns the facetLocalPartioning array.
  20404. */
  20405. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20406. if (!this._facetPartitioning) {
  20407. this.updateFacetData();
  20408. }
  20409. return this._facetPartitioning;
  20410. };
  20411. /**
  20412. * Returns the i-th facet position in the world system.
  20413. * This method allocates a new Vector3 per call.
  20414. */
  20415. AbstractMesh.prototype.getFacetPosition = function (i) {
  20416. var pos = BABYLON.Vector3.Zero();
  20417. this.getFacetPositionToRef(i, pos);
  20418. return pos;
  20419. };
  20420. /**
  20421. * Sets the reference Vector3 with the i-th facet position in the world system.
  20422. * Returns the AbstractMesh.
  20423. */
  20424. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20425. var localPos = (this.getFacetLocalPositions())[i];
  20426. var world = this.getWorldMatrix();
  20427. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20428. return this;
  20429. };
  20430. /**
  20431. * Returns the i-th facet normal in the world system.
  20432. * This method allocates a new Vector3 per call.
  20433. */
  20434. AbstractMesh.prototype.getFacetNormal = function (i) {
  20435. var norm = BABYLON.Vector3.Zero();
  20436. this.getFacetNormalToRef(i, norm);
  20437. return norm;
  20438. };
  20439. /**
  20440. * Sets the reference Vector3 with the i-th facet normal in the world system.
  20441. * Returns the AbstractMesh.
  20442. */
  20443. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20444. var localNorm = (this.getFacetLocalNormals())[i];
  20445. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20446. return this;
  20447. };
  20448. /**
  20449. * 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).
  20450. */
  20451. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20452. var bInfo = this.getBoundingInfo();
  20453. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20454. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20455. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20456. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20457. return null;
  20458. }
  20459. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20460. };
  20461. /**
  20462. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  20463. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  20464. * If checkFace is 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.
  20465. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20466. * 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.
  20467. */
  20468. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20469. if (checkFace === void 0) { checkFace = false; }
  20470. if (facing === void 0) { facing = true; }
  20471. var world = this.getWorldMatrix();
  20472. var invMat = BABYLON.Tmp.Matrix[5];
  20473. world.invertToRef(invMat);
  20474. var invVect = BABYLON.Tmp.Vector3[8];
  20475. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20476. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20477. if (projected) {
  20478. // tranform the local computed projected vector to world coordinates
  20479. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20480. }
  20481. return closest;
  20482. };
  20483. /**
  20484. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  20485. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  20486. * If checkFace is 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.
  20487. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20488. * 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.
  20489. */
  20490. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20491. if (checkFace === void 0) { checkFace = false; }
  20492. if (facing === void 0) { facing = true; }
  20493. var closest = null;
  20494. var tmpx = 0.0;
  20495. var tmpy = 0.0;
  20496. var tmpz = 0.0;
  20497. var d = 0.0; // tmp dot facet normal * facet position
  20498. var t0 = 0.0;
  20499. var projx = 0.0;
  20500. var projy = 0.0;
  20501. var projz = 0.0;
  20502. // Get all the facets in the same partitioning block than (x, y, z)
  20503. var facetPositions = this.getFacetLocalPositions();
  20504. var facetNormals = this.getFacetLocalNormals();
  20505. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20506. if (!facetsInBlock) {
  20507. return null;
  20508. }
  20509. // Get the closest facet to (x, y, z)
  20510. var shortest = Number.MAX_VALUE; // init distance vars
  20511. var tmpDistance = shortest;
  20512. var fib; // current facet in the block
  20513. var norm; // current facet normal
  20514. var p0; // current facet barycenter position
  20515. // loop on all the facets in the current partitioning block
  20516. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20517. fib = facetsInBlock[idx];
  20518. norm = facetNormals[fib];
  20519. p0 = facetPositions[fib];
  20520. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20521. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20522. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20523. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20524. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20525. projx = x + norm.x * t0;
  20526. projy = y + norm.y * t0;
  20527. projz = z + norm.z * t0;
  20528. tmpx = projx - x;
  20529. tmpy = projy - y;
  20530. tmpz = projz - z;
  20531. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20532. if (tmpDistance < shortest) {
  20533. shortest = tmpDistance;
  20534. closest = fib;
  20535. if (projected) {
  20536. projected.x = projx;
  20537. projected.y = projy;
  20538. projected.z = projz;
  20539. }
  20540. }
  20541. }
  20542. }
  20543. return closest;
  20544. };
  20545. /**
  20546. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20547. */
  20548. AbstractMesh.prototype.getFacetDataParameters = function () {
  20549. return this._facetParameters;
  20550. };
  20551. /**
  20552. * Disables the feature FacetData and frees the related memory.
  20553. * Returns the AbstractMesh.
  20554. */
  20555. AbstractMesh.prototype.disableFacetData = function () {
  20556. if (this._facetDataEnabled) {
  20557. this._facetDataEnabled = false;
  20558. this._facetPositions = new Array();
  20559. this._facetNormals = new Array();
  20560. this._facetPartitioning = new Array();
  20561. this._facetParameters = null;
  20562. this._depthSortedIndices = new Uint32Array(0);
  20563. }
  20564. return this;
  20565. };
  20566. /**
  20567. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  20568. * Returns the mesh.
  20569. */
  20570. AbstractMesh.prototype.updateIndices = function (indices) {
  20571. return this;
  20572. };
  20573. /**
  20574. * The mesh Geometry. Actually used by the Mesh object.
  20575. * Returns a blank geometry object.
  20576. */
  20577. /**
  20578. * Creates new normals data for the mesh.
  20579. * @param updatable.
  20580. */
  20581. AbstractMesh.prototype.createNormals = function (updatable) {
  20582. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20583. var indices = this.getIndices();
  20584. var normals;
  20585. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20586. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20587. }
  20588. else {
  20589. normals = [];
  20590. }
  20591. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20592. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20593. };
  20594. /**
  20595. * Align the mesh with a normal.
  20596. * Returns the mesh.
  20597. */
  20598. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20599. if (!upDirection) {
  20600. upDirection = BABYLON.Axis.Y;
  20601. }
  20602. var axisX = BABYLON.Tmp.Vector3[0];
  20603. var axisZ = BABYLON.Tmp.Vector3[1];
  20604. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20605. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20606. if (this.rotationQuaternion) {
  20607. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20608. }
  20609. else {
  20610. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20611. }
  20612. return this;
  20613. };
  20614. AbstractMesh.prototype.checkOcclusionQuery = function () {
  20615. var engine = this.getEngine();
  20616. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20617. this._isOccluded = false;
  20618. return;
  20619. }
  20620. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20621. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20622. if (isOcclusionQueryAvailable) {
  20623. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20624. this._isOcclusionQueryInProgress = false;
  20625. this._occlusionInternalRetryCounter = 0;
  20626. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20627. }
  20628. else {
  20629. this._occlusionInternalRetryCounter++;
  20630. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20631. this._isOcclusionQueryInProgress = false;
  20632. this._occlusionInternalRetryCounter = 0;
  20633. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20634. // if strict continue the last state of the object.
  20635. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20636. }
  20637. else {
  20638. return;
  20639. }
  20640. }
  20641. }
  20642. var scene = this.getScene();
  20643. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20644. if (!this._occlusionQuery) {
  20645. this._occlusionQuery = engine.createQuery();
  20646. }
  20647. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20648. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20649. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20650. this._isOcclusionQueryInProgress = true;
  20651. };
  20652. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20653. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20654. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20655. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20656. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20657. return AbstractMesh;
  20658. }(BABYLON.TransformNode));
  20659. BABYLON.AbstractMesh = AbstractMesh;
  20660. })(BABYLON || (BABYLON = {}));
  20661. //# sourceMappingURL=babylon.abstractMesh.js.map
  20662. "use strict";
  20663. var BABYLON;
  20664. (function (BABYLON) {
  20665. /**
  20666. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  20667. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  20668. * 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.
  20669. */
  20670. var Light = /** @class */ (function (_super) {
  20671. __extends(Light, _super);
  20672. /**
  20673. * Creates a Light object in the scene.
  20674. * Documentation : http://doc.babylonjs.com/tutorials/lights
  20675. * @param name The firendly name of the light
  20676. * @param scene The scene the light belongs too
  20677. */
  20678. function Light(name, scene) {
  20679. var _this = _super.call(this, name, scene) || this;
  20680. /**
  20681. * Diffuse gives the basic color to an object.
  20682. */
  20683. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  20684. /**
  20685. * Specular produces a highlight color on an object.
  20686. * Note: This is note affecting PBR materials.
  20687. */
  20688. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  20689. /**
  20690. * Strength of the light.
  20691. * Note: By default it is define in the framework own unit.
  20692. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  20693. */
  20694. _this.intensity = 1.0;
  20695. /**
  20696. * Defines how far from the source the light is impacting in scene units.
  20697. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  20698. */
  20699. _this.range = Number.MAX_VALUE;
  20700. /**
  20701. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  20702. * of light.
  20703. */
  20704. _this._photometricScale = 1.0;
  20705. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  20706. _this._radius = 0.00001;
  20707. /**
  20708. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  20709. * exceeding the number allowed of the materials.
  20710. */
  20711. _this.renderPriority = 0;
  20712. /**
  20713. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  20714. * the current shadow generator.
  20715. */
  20716. _this.shadowEnabled = true;
  20717. _this._excludeWithLayerMask = 0;
  20718. _this._includeOnlyWithLayerMask = 0;
  20719. _this._lightmapMode = 0;
  20720. /**
  20721. * @ignore Internal use only.
  20722. */
  20723. _this._excludedMeshesIds = new Array();
  20724. /**
  20725. * @ignore Internal use only.
  20726. */
  20727. _this._includedOnlyMeshesIds = new Array();
  20728. _this.getScene().addLight(_this);
  20729. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  20730. _this._buildUniformLayout();
  20731. _this.includedOnlyMeshes = new Array();
  20732. _this.excludedMeshes = new Array();
  20733. _this._resyncMeshes();
  20734. return _this;
  20735. }
  20736. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  20737. /**
  20738. * If every light affecting the material is in this lightmapMode,
  20739. * material.lightmapTexture adds or multiplies
  20740. * (depends on material.useLightmapAsShadowmap)
  20741. * after every other light calculations.
  20742. */
  20743. get: function () {
  20744. return Light._LIGHTMAP_DEFAULT;
  20745. },
  20746. enumerable: true,
  20747. configurable: true
  20748. });
  20749. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  20750. /**
  20751. * material.lightmapTexture as only diffuse lighting from this light
  20752. * adds only specular lighting from this light
  20753. * adds dynamic shadows
  20754. */
  20755. get: function () {
  20756. return Light._LIGHTMAP_SPECULAR;
  20757. },
  20758. enumerable: true,
  20759. configurable: true
  20760. });
  20761. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  20762. /**
  20763. * material.lightmapTexture as only lighting
  20764. * no light calculation from this light
  20765. * only adds dynamic shadows from this light
  20766. */
  20767. get: function () {
  20768. return Light._LIGHTMAP_SHADOWSONLY;
  20769. },
  20770. enumerable: true,
  20771. configurable: true
  20772. });
  20773. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  20774. /**
  20775. * Each light type uses the default quantity according to its type:
  20776. * point/spot lights use luminous intensity
  20777. * directional lights use illuminance
  20778. */
  20779. get: function () {
  20780. return Light._INTENSITYMODE_AUTOMATIC;
  20781. },
  20782. enumerable: true,
  20783. configurable: true
  20784. });
  20785. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  20786. /**
  20787. * lumen (lm)
  20788. */
  20789. get: function () {
  20790. return Light._INTENSITYMODE_LUMINOUSPOWER;
  20791. },
  20792. enumerable: true,
  20793. configurable: true
  20794. });
  20795. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  20796. /**
  20797. * candela (lm/sr)
  20798. */
  20799. get: function () {
  20800. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  20801. },
  20802. enumerable: true,
  20803. configurable: true
  20804. });
  20805. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  20806. /**
  20807. * lux (lm/m^2)
  20808. */
  20809. get: function () {
  20810. return Light._INTENSITYMODE_ILLUMINANCE;
  20811. },
  20812. enumerable: true,
  20813. configurable: true
  20814. });
  20815. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  20816. /**
  20817. * nit (cd/m^2)
  20818. */
  20819. get: function () {
  20820. return Light._INTENSITYMODE_LUMINANCE;
  20821. },
  20822. enumerable: true,
  20823. configurable: true
  20824. });
  20825. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  20826. /**
  20827. * Light type const id of the point light.
  20828. */
  20829. get: function () {
  20830. return Light._LIGHTTYPEID_POINTLIGHT;
  20831. },
  20832. enumerable: true,
  20833. configurable: true
  20834. });
  20835. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  20836. /**
  20837. * Light type const id of the directional light.
  20838. */
  20839. get: function () {
  20840. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  20841. },
  20842. enumerable: true,
  20843. configurable: true
  20844. });
  20845. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  20846. /**
  20847. * Light type const id of the spot light.
  20848. */
  20849. get: function () {
  20850. return Light._LIGHTTYPEID_SPOTLIGHT;
  20851. },
  20852. enumerable: true,
  20853. configurable: true
  20854. });
  20855. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  20856. /**
  20857. * Light type const id of the hemispheric light.
  20858. */
  20859. get: function () {
  20860. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  20861. },
  20862. enumerable: true,
  20863. configurable: true
  20864. });
  20865. Object.defineProperty(Light.prototype, "intensityMode", {
  20866. /**
  20867. * Gets the photometric scale used to interpret the intensity.
  20868. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20869. */
  20870. get: function () {
  20871. return this._intensityMode;
  20872. },
  20873. /**
  20874. * Sets the photometric scale used to interpret the intensity.
  20875. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20876. */
  20877. set: function (value) {
  20878. this._intensityMode = value;
  20879. this._computePhotometricScale();
  20880. },
  20881. enumerable: true,
  20882. configurable: true
  20883. });
  20884. ;
  20885. ;
  20886. Object.defineProperty(Light.prototype, "radius", {
  20887. /**
  20888. * Gets the light radius used by PBR Materials to simulate soft area lights.
  20889. */
  20890. get: function () {
  20891. return this._radius;
  20892. },
  20893. /**
  20894. * sets the light radius used by PBR Materials to simulate soft area lights.
  20895. */
  20896. set: function (value) {
  20897. this._radius = value;
  20898. this._computePhotometricScale();
  20899. },
  20900. enumerable: true,
  20901. configurable: true
  20902. });
  20903. ;
  20904. ;
  20905. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  20906. /**
  20907. * Gets the only meshes impacted by this light.
  20908. */
  20909. get: function () {
  20910. return this._includedOnlyMeshes;
  20911. },
  20912. /**
  20913. * Sets the only meshes impacted by this light.
  20914. */
  20915. set: function (value) {
  20916. this._includedOnlyMeshes = value;
  20917. this._hookArrayForIncludedOnly(value);
  20918. },
  20919. enumerable: true,
  20920. configurable: true
  20921. });
  20922. Object.defineProperty(Light.prototype, "excludedMeshes", {
  20923. /**
  20924. * Gets the meshes not impacted by this light.
  20925. */
  20926. get: function () {
  20927. return this._excludedMeshes;
  20928. },
  20929. /**
  20930. * Sets the meshes not impacted by this light.
  20931. */
  20932. set: function (value) {
  20933. this._excludedMeshes = value;
  20934. this._hookArrayForExcluded(value);
  20935. },
  20936. enumerable: true,
  20937. configurable: true
  20938. });
  20939. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  20940. /**
  20941. * Gets the layer id use to find what meshes are not impacted by the light.
  20942. * Inactive if 0
  20943. */
  20944. get: function () {
  20945. return this._excludeWithLayerMask;
  20946. },
  20947. /**
  20948. * Sets the layer id use to find what meshes are not impacted by the light.
  20949. * Inactive if 0
  20950. */
  20951. set: function (value) {
  20952. this._excludeWithLayerMask = value;
  20953. this._resyncMeshes();
  20954. },
  20955. enumerable: true,
  20956. configurable: true
  20957. });
  20958. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  20959. /**
  20960. * Gets the layer id use to find what meshes are impacted by the light.
  20961. * Inactive if 0
  20962. */
  20963. get: function () {
  20964. return this._includeOnlyWithLayerMask;
  20965. },
  20966. /**
  20967. * Sets the layer id use to find what meshes are impacted by the light.
  20968. * Inactive if 0
  20969. */
  20970. set: function (value) {
  20971. this._includeOnlyWithLayerMask = value;
  20972. this._resyncMeshes();
  20973. },
  20974. enumerable: true,
  20975. configurable: true
  20976. });
  20977. Object.defineProperty(Light.prototype, "lightmapMode", {
  20978. /**
  20979. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  20980. */
  20981. get: function () {
  20982. return this._lightmapMode;
  20983. },
  20984. /**
  20985. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  20986. */
  20987. set: function (value) {
  20988. if (this._lightmapMode === value) {
  20989. return;
  20990. }
  20991. this._lightmapMode = value;
  20992. this._markMeshesAsLightDirty();
  20993. },
  20994. enumerable: true,
  20995. configurable: true
  20996. });
  20997. /**
  20998. * Returns the string "Light".
  20999. * @returns the class name
  21000. */
  21001. Light.prototype.getClassName = function () {
  21002. return "Light";
  21003. };
  21004. /**
  21005. * Converts the light information to a readable string for debug purpose.
  21006. * @param fullDetails Supports for multiple levels of logging within scene loading
  21007. * @returns the human readable light info
  21008. */
  21009. Light.prototype.toString = function (fullDetails) {
  21010. var ret = "Name: " + this.name;
  21011. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21012. if (this.animations) {
  21013. for (var i = 0; i < this.animations.length; i++) {
  21014. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21015. }
  21016. }
  21017. if (fullDetails) {
  21018. }
  21019. return ret;
  21020. };
  21021. /**
  21022. * Set the enabled state of this node.
  21023. * @param value - the new enabled state
  21024. */
  21025. Light.prototype.setEnabled = function (value) {
  21026. _super.prototype.setEnabled.call(this, value);
  21027. this._resyncMeshes();
  21028. };
  21029. /**
  21030. * Returns the Light associated shadow generator if any.
  21031. * @return the associated shadow generator.
  21032. */
  21033. Light.prototype.getShadowGenerator = function () {
  21034. return this._shadowGenerator;
  21035. };
  21036. /**
  21037. * Returns a Vector3, the absolute light position in the World.
  21038. * @returns the world space position of the light
  21039. */
  21040. Light.prototype.getAbsolutePosition = function () {
  21041. return BABYLON.Vector3.Zero();
  21042. };
  21043. /**
  21044. * Specifies if the light will affect the passed mesh.
  21045. * @param mesh The mesh to test against the light
  21046. * @return true the mesh is affected otherwise, false.
  21047. */
  21048. Light.prototype.canAffectMesh = function (mesh) {
  21049. if (!mesh) {
  21050. return true;
  21051. }
  21052. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21053. return false;
  21054. }
  21055. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21056. return false;
  21057. }
  21058. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21059. return false;
  21060. }
  21061. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21062. return false;
  21063. }
  21064. return true;
  21065. };
  21066. /**
  21067. * Computes and Returns the light World matrix.
  21068. * @returns the world matrix
  21069. */
  21070. Light.prototype.getWorldMatrix = function () {
  21071. this._currentRenderId = this.getScene().getRenderId();
  21072. this._childRenderId = this._currentRenderId;
  21073. var worldMatrix = this._getWorldMatrix();
  21074. if (this.parent && this.parent.getWorldMatrix) {
  21075. if (!this._parentedWorldMatrix) {
  21076. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21077. }
  21078. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21079. this._markSyncedWithParent();
  21080. return this._parentedWorldMatrix;
  21081. }
  21082. return worldMatrix;
  21083. };
  21084. /**
  21085. * Sort function to order lights for rendering.
  21086. * @param a First Light object to compare to second.
  21087. * @param b Second Light object to compare first.
  21088. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21089. */
  21090. Light.CompareLightsPriority = function (a, b) {
  21091. //shadow-casting lights have priority over non-shadow-casting lights
  21092. //the renderPrioirty is a secondary sort criterion
  21093. if (a.shadowEnabled !== b.shadowEnabled) {
  21094. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21095. }
  21096. return b.renderPriority - a.renderPriority;
  21097. };
  21098. /**
  21099. * Releases resources associated with this node.
  21100. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21101. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21102. */
  21103. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21104. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21105. if (this._shadowGenerator) {
  21106. this._shadowGenerator.dispose();
  21107. this._shadowGenerator = null;
  21108. }
  21109. // Animations
  21110. this.getScene().stopAnimation(this);
  21111. // Remove from meshes
  21112. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21113. var mesh = _a[_i];
  21114. mesh._removeLightSource(this);
  21115. }
  21116. this._uniformBuffer.dispose();
  21117. // Remove from scene
  21118. this.getScene().removeLight(this);
  21119. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21120. };
  21121. /**
  21122. * Returns the light type ID (integer).
  21123. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21124. */
  21125. Light.prototype.getTypeID = function () {
  21126. return 0;
  21127. };
  21128. /**
  21129. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21130. * @returns the scaled intensity in intensity mode unit
  21131. */
  21132. Light.prototype.getScaledIntensity = function () {
  21133. return this._photometricScale * this.intensity;
  21134. };
  21135. /**
  21136. * Returns a new Light object, named "name", from the current one.
  21137. * @param name The name of the cloned light
  21138. * @returns the new created light
  21139. */
  21140. Light.prototype.clone = function (name) {
  21141. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21142. if (!constructor) {
  21143. return null;
  21144. }
  21145. return BABYLON.SerializationHelper.Clone(constructor, this);
  21146. };
  21147. /**
  21148. * Serializes the current light into a Serialization object.
  21149. * @returns the serialized object.
  21150. */
  21151. Light.prototype.serialize = function () {
  21152. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21153. // Type
  21154. serializationObject.type = this.getTypeID();
  21155. // Parent
  21156. if (this.parent) {
  21157. serializationObject.parentId = this.parent.id;
  21158. }
  21159. // Inclusion / exclusions
  21160. if (this.excludedMeshes.length > 0) {
  21161. serializationObject.excludedMeshesIds = [];
  21162. this.excludedMeshes.forEach(function (mesh) {
  21163. serializationObject.excludedMeshesIds.push(mesh.id);
  21164. });
  21165. }
  21166. if (this.includedOnlyMeshes.length > 0) {
  21167. serializationObject.includedOnlyMeshesIds = [];
  21168. this.includedOnlyMeshes.forEach(function (mesh) {
  21169. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21170. });
  21171. }
  21172. // Animations
  21173. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21174. serializationObject.ranges = this.serializeAnimationRanges();
  21175. return serializationObject;
  21176. };
  21177. /**
  21178. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21179. * This new light is named "name" and added to the passed scene.
  21180. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21181. * @param name The friendly name of the light
  21182. * @param scene The scene the new light will belong to
  21183. * @returns the constructor function
  21184. */
  21185. Light.GetConstructorFromName = function (type, name, scene) {
  21186. switch (type) {
  21187. case 0:
  21188. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21189. case 1:
  21190. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21191. case 2:
  21192. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21193. case 3:
  21194. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21195. }
  21196. return null;
  21197. };
  21198. /**
  21199. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21200. * @param parsedLight The JSON representation of the light
  21201. * @param scene The scene to create the parsed light in
  21202. * @returns the created light after parsing
  21203. */
  21204. Light.Parse = function (parsedLight, scene) {
  21205. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21206. if (!constructor) {
  21207. return null;
  21208. }
  21209. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21210. // Inclusion / exclusions
  21211. if (parsedLight.excludedMeshesIds) {
  21212. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21213. }
  21214. if (parsedLight.includedOnlyMeshesIds) {
  21215. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21216. }
  21217. // Parent
  21218. if (parsedLight.parentId) {
  21219. light._waitingParentId = parsedLight.parentId;
  21220. }
  21221. // Animations
  21222. if (parsedLight.animations) {
  21223. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21224. var parsedAnimation = parsedLight.animations[animationIndex];
  21225. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21226. }
  21227. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21228. }
  21229. if (parsedLight.autoAnimate) {
  21230. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21231. }
  21232. return light;
  21233. };
  21234. Light.prototype._hookArrayForExcluded = function (array) {
  21235. var _this = this;
  21236. var oldPush = array.push;
  21237. array.push = function () {
  21238. var items = [];
  21239. for (var _i = 0; _i < arguments.length; _i++) {
  21240. items[_i] = arguments[_i];
  21241. }
  21242. var result = oldPush.apply(array, items);
  21243. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21244. var item = items_1[_a];
  21245. item._resyncLighSource(_this);
  21246. }
  21247. return result;
  21248. };
  21249. var oldSplice = array.splice;
  21250. array.splice = function (index, deleteCount) {
  21251. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21252. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21253. var item = deleted_1[_i];
  21254. item._resyncLighSource(_this);
  21255. }
  21256. return deleted;
  21257. };
  21258. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21259. var item = array_1[_i];
  21260. item._resyncLighSource(this);
  21261. }
  21262. };
  21263. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21264. var _this = this;
  21265. var oldPush = array.push;
  21266. array.push = function () {
  21267. var items = [];
  21268. for (var _i = 0; _i < arguments.length; _i++) {
  21269. items[_i] = arguments[_i];
  21270. }
  21271. var result = oldPush.apply(array, items);
  21272. _this._resyncMeshes();
  21273. return result;
  21274. };
  21275. var oldSplice = array.splice;
  21276. array.splice = function (index, deleteCount) {
  21277. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21278. _this._resyncMeshes();
  21279. return deleted;
  21280. };
  21281. this._resyncMeshes();
  21282. };
  21283. Light.prototype._resyncMeshes = function () {
  21284. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21285. var mesh = _a[_i];
  21286. mesh._resyncLighSource(this);
  21287. }
  21288. };
  21289. /**
  21290. * Forces the meshes to update their light related information in their rendering used effects
  21291. * @ignore Internal Use Only
  21292. */
  21293. Light.prototype._markMeshesAsLightDirty = function () {
  21294. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21295. var mesh = _a[_i];
  21296. if (mesh._lightSources.indexOf(this) !== -1) {
  21297. mesh._markSubMeshesAsLightDirty();
  21298. }
  21299. }
  21300. };
  21301. /**
  21302. * Recomputes the cached photometric scale if needed.
  21303. */
  21304. Light.prototype._computePhotometricScale = function () {
  21305. this._photometricScale = this._getPhotometricScale();
  21306. this.getScene().resetCachedMaterial();
  21307. };
  21308. /**
  21309. * Returns the Photometric Scale according to the light type and intensity mode.
  21310. */
  21311. Light.prototype._getPhotometricScale = function () {
  21312. var photometricScale = 0.0;
  21313. var lightTypeID = this.getTypeID();
  21314. //get photometric mode
  21315. var photometricMode = this.intensityMode;
  21316. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21317. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21318. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21319. }
  21320. else {
  21321. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21322. }
  21323. }
  21324. //compute photometric scale
  21325. switch (lightTypeID) {
  21326. case Light.LIGHTTYPEID_POINTLIGHT:
  21327. case Light.LIGHTTYPEID_SPOTLIGHT:
  21328. switch (photometricMode) {
  21329. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21330. photometricScale = 1.0 / (4.0 * Math.PI);
  21331. break;
  21332. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21333. photometricScale = 1.0;
  21334. break;
  21335. case Light.INTENSITYMODE_LUMINANCE:
  21336. photometricScale = this.radius * this.radius;
  21337. break;
  21338. }
  21339. break;
  21340. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21341. switch (photometricMode) {
  21342. case Light.INTENSITYMODE_ILLUMINANCE:
  21343. photometricScale = 1.0;
  21344. break;
  21345. case Light.INTENSITYMODE_LUMINANCE:
  21346. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21347. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21348. var apexAngleRadians = this.radius;
  21349. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21350. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21351. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21352. photometricScale = solidAngle;
  21353. break;
  21354. }
  21355. break;
  21356. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21357. // No fall off in hemisperic light.
  21358. photometricScale = 1.0;
  21359. break;
  21360. }
  21361. return photometricScale;
  21362. };
  21363. /**
  21364. * Reorder the light in the scene according to their defined priority.
  21365. * @ignore Internal Use Only
  21366. */
  21367. Light.prototype._reorderLightsInScene = function () {
  21368. var scene = this.getScene();
  21369. if (this._renderPriority != 0) {
  21370. scene.requireLightSorting = true;
  21371. }
  21372. this.getScene().sortLightsByPriority();
  21373. };
  21374. //lightmapMode Consts
  21375. Light._LIGHTMAP_DEFAULT = 0;
  21376. Light._LIGHTMAP_SPECULAR = 1;
  21377. Light._LIGHTMAP_SHADOWSONLY = 2;
  21378. // Intensity Mode Consts
  21379. Light._INTENSITYMODE_AUTOMATIC = 0;
  21380. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21381. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21382. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21383. Light._INTENSITYMODE_LUMINANCE = 4;
  21384. // Light types ids const.
  21385. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21386. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21387. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21388. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21389. __decorate([
  21390. BABYLON.serializeAsColor3()
  21391. ], Light.prototype, "diffuse", void 0);
  21392. __decorate([
  21393. BABYLON.serializeAsColor3()
  21394. ], Light.prototype, "specular", void 0);
  21395. __decorate([
  21396. BABYLON.serialize()
  21397. ], Light.prototype, "intensity", void 0);
  21398. __decorate([
  21399. BABYLON.serialize()
  21400. ], Light.prototype, "range", void 0);
  21401. __decorate([
  21402. BABYLON.serialize()
  21403. ], Light.prototype, "intensityMode", null);
  21404. __decorate([
  21405. BABYLON.serialize()
  21406. ], Light.prototype, "radius", null);
  21407. __decorate([
  21408. BABYLON.serialize()
  21409. ], Light.prototype, "_renderPriority", void 0);
  21410. __decorate([
  21411. BABYLON.expandToProperty("_reorderLightsInScene")
  21412. ], Light.prototype, "renderPriority", void 0);
  21413. __decorate([
  21414. BABYLON.serialize()
  21415. ], Light.prototype, "shadowEnabled", void 0);
  21416. __decorate([
  21417. BABYLON.serialize("excludeWithLayerMask")
  21418. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21419. __decorate([
  21420. BABYLON.serialize("includeOnlyWithLayerMask")
  21421. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21422. __decorate([
  21423. BABYLON.serialize("lightmapMode")
  21424. ], Light.prototype, "_lightmapMode", void 0);
  21425. return Light;
  21426. }(BABYLON.Node));
  21427. BABYLON.Light = Light;
  21428. })(BABYLON || (BABYLON = {}));
  21429. //# sourceMappingURL=babylon.light.js.map
  21430. "use strict";
  21431. var BABYLON;
  21432. (function (BABYLON) {
  21433. var Camera = /** @class */ (function (_super) {
  21434. __extends(Camera, _super);
  21435. function Camera(name, position, scene) {
  21436. var _this = _super.call(this, name, scene) || this;
  21437. /**
  21438. * The vector the camera should consider as up.
  21439. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21440. */
  21441. _this.upVector = BABYLON.Vector3.Up();
  21442. _this.orthoLeft = null;
  21443. _this.orthoRight = null;
  21444. _this.orthoBottom = null;
  21445. _this.orthoTop = null;
  21446. /**
  21447. * FOV is set in Radians. (default is 0.8)
  21448. */
  21449. _this.fov = 0.8;
  21450. _this.minZ = 1;
  21451. _this.maxZ = 10000.0;
  21452. _this.inertia = 0.9;
  21453. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21454. _this.isIntermediate = false;
  21455. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21456. /**
  21457. * Restricts the camera to viewing objects with the same layerMask.
  21458. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21459. */
  21460. _this.layerMask = 0x0FFFFFFF;
  21461. /**
  21462. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21463. */
  21464. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21465. // Camera rig members
  21466. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21467. _this._rigCameras = new Array();
  21468. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21469. _this._skipRendering = false;
  21470. _this.customRenderTargets = new Array();
  21471. // Observables
  21472. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21473. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21474. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21475. _this.onRestoreStateObservable = new BABYLON.Observable();
  21476. // Cache
  21477. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21478. _this._projectionMatrix = new BABYLON.Matrix();
  21479. _this._doNotComputeProjectionMatrix = false;
  21480. _this._postProcesses = new Array();
  21481. _this._transformMatrix = BABYLON.Matrix.Zero();
  21482. _this._activeMeshes = new BABYLON.SmartArray(256);
  21483. _this._globalPosition = BABYLON.Vector3.Zero();
  21484. _this._refreshFrustumPlanes = true;
  21485. _this.getScene().addCamera(_this);
  21486. if (!_this.getScene().activeCamera) {
  21487. _this.getScene().activeCamera = _this;
  21488. }
  21489. _this.position = position;
  21490. return _this;
  21491. }
  21492. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21493. get: function () {
  21494. return Camera._PERSPECTIVE_CAMERA;
  21495. },
  21496. enumerable: true,
  21497. configurable: true
  21498. });
  21499. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21500. get: function () {
  21501. return Camera._ORTHOGRAPHIC_CAMERA;
  21502. },
  21503. enumerable: true,
  21504. configurable: true
  21505. });
  21506. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21507. /**
  21508. * This is the default FOV mode for perspective cameras.
  21509. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21510. *
  21511. */
  21512. get: function () {
  21513. return Camera._FOVMODE_VERTICAL_FIXED;
  21514. },
  21515. enumerable: true,
  21516. configurable: true
  21517. });
  21518. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21519. /**
  21520. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21521. *
  21522. */
  21523. get: function () {
  21524. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21525. },
  21526. enumerable: true,
  21527. configurable: true
  21528. });
  21529. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21530. get: function () {
  21531. return Camera._RIG_MODE_NONE;
  21532. },
  21533. enumerable: true,
  21534. configurable: true
  21535. });
  21536. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21537. get: function () {
  21538. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21539. },
  21540. enumerable: true,
  21541. configurable: true
  21542. });
  21543. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21544. get: function () {
  21545. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21546. },
  21547. enumerable: true,
  21548. configurable: true
  21549. });
  21550. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21551. get: function () {
  21552. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21553. },
  21554. enumerable: true,
  21555. configurable: true
  21556. });
  21557. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21558. get: function () {
  21559. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21560. },
  21561. enumerable: true,
  21562. configurable: true
  21563. });
  21564. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21565. get: function () {
  21566. return Camera._RIG_MODE_VR;
  21567. },
  21568. enumerable: true,
  21569. configurable: true
  21570. });
  21571. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21572. get: function () {
  21573. return Camera._RIG_MODE_WEBVR;
  21574. },
  21575. enumerable: true,
  21576. configurable: true
  21577. });
  21578. /**
  21579. * Store current camera state (fov, position, etc..)
  21580. */
  21581. Camera.prototype.storeState = function () {
  21582. this._stateStored = true;
  21583. this._storedFov = this.fov;
  21584. return this;
  21585. };
  21586. /**
  21587. * Restores the camera state values if it has been stored. You must call storeState() first
  21588. */
  21589. Camera.prototype._restoreStateValues = function () {
  21590. if (!this._stateStored) {
  21591. return false;
  21592. }
  21593. this.fov = this._storedFov;
  21594. return true;
  21595. };
  21596. /**
  21597. * Restored camera state. You must call storeState() first
  21598. */
  21599. Camera.prototype.restoreState = function () {
  21600. if (this._restoreStateValues()) {
  21601. this.onRestoreStateObservable.notifyObservers(this);
  21602. return true;
  21603. }
  21604. return false;
  21605. };
  21606. Camera.prototype.getClassName = function () {
  21607. return "Camera";
  21608. };
  21609. /**
  21610. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21611. */
  21612. Camera.prototype.toString = function (fullDetails) {
  21613. var ret = "Name: " + this.name;
  21614. ret += ", type: " + this.getClassName();
  21615. if (this.animations) {
  21616. for (var i = 0; i < this.animations.length; i++) {
  21617. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21618. }
  21619. }
  21620. if (fullDetails) {
  21621. }
  21622. return ret;
  21623. };
  21624. Object.defineProperty(Camera.prototype, "globalPosition", {
  21625. get: function () {
  21626. return this._globalPosition;
  21627. },
  21628. enumerable: true,
  21629. configurable: true
  21630. });
  21631. Camera.prototype.getActiveMeshes = function () {
  21632. return this._activeMeshes;
  21633. };
  21634. Camera.prototype.isActiveMesh = function (mesh) {
  21635. return (this._activeMeshes.indexOf(mesh) !== -1);
  21636. };
  21637. /**
  21638. * Is this camera ready to be used/rendered
  21639. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21640. * @return true if the camera is ready
  21641. */
  21642. Camera.prototype.isReady = function (completeCheck) {
  21643. if (completeCheck === void 0) { completeCheck = false; }
  21644. if (completeCheck) {
  21645. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21646. var pp = _a[_i];
  21647. if (pp && !pp.isReady()) {
  21648. return false;
  21649. }
  21650. }
  21651. }
  21652. return _super.prototype.isReady.call(this, completeCheck);
  21653. };
  21654. //Cache
  21655. Camera.prototype._initCache = function () {
  21656. _super.prototype._initCache.call(this);
  21657. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21658. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21659. this._cache.mode = undefined;
  21660. this._cache.minZ = undefined;
  21661. this._cache.maxZ = undefined;
  21662. this._cache.fov = undefined;
  21663. this._cache.fovMode = undefined;
  21664. this._cache.aspectRatio = undefined;
  21665. this._cache.orthoLeft = undefined;
  21666. this._cache.orthoRight = undefined;
  21667. this._cache.orthoBottom = undefined;
  21668. this._cache.orthoTop = undefined;
  21669. this._cache.renderWidth = undefined;
  21670. this._cache.renderHeight = undefined;
  21671. };
  21672. Camera.prototype._updateCache = function (ignoreParentClass) {
  21673. if (!ignoreParentClass) {
  21674. _super.prototype._updateCache.call(this);
  21675. }
  21676. this._cache.position.copyFrom(this.position);
  21677. this._cache.upVector.copyFrom(this.upVector);
  21678. };
  21679. // Synchronized
  21680. Camera.prototype._isSynchronized = function () {
  21681. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  21682. };
  21683. Camera.prototype._isSynchronizedViewMatrix = function () {
  21684. if (!_super.prototype._isSynchronized.call(this))
  21685. return false;
  21686. return this._cache.position.equals(this.position)
  21687. && this._cache.upVector.equals(this.upVector)
  21688. && this.isSynchronizedWithParent();
  21689. };
  21690. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  21691. var check = this._cache.mode === this.mode
  21692. && this._cache.minZ === this.minZ
  21693. && this._cache.maxZ === this.maxZ;
  21694. if (!check) {
  21695. return false;
  21696. }
  21697. var engine = this.getEngine();
  21698. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21699. check = this._cache.fov === this.fov
  21700. && this._cache.fovMode === this.fovMode
  21701. && this._cache.aspectRatio === engine.getAspectRatio(this);
  21702. }
  21703. else {
  21704. check = this._cache.orthoLeft === this.orthoLeft
  21705. && this._cache.orthoRight === this.orthoRight
  21706. && this._cache.orthoBottom === this.orthoBottom
  21707. && this._cache.orthoTop === this.orthoTop
  21708. && this._cache.renderWidth === engine.getRenderWidth()
  21709. && this._cache.renderHeight === engine.getRenderHeight();
  21710. }
  21711. return check;
  21712. };
  21713. // Controls
  21714. Camera.prototype.attachControl = function (element, noPreventDefault) {
  21715. };
  21716. Camera.prototype.detachControl = function (element) {
  21717. };
  21718. Camera.prototype.update = function () {
  21719. this._checkInputs();
  21720. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21721. this._updateRigCameras();
  21722. }
  21723. };
  21724. Camera.prototype._checkInputs = function () {
  21725. this.onAfterCheckInputsObservable.notifyObservers(this);
  21726. };
  21727. Object.defineProperty(Camera.prototype, "rigCameras", {
  21728. get: function () {
  21729. return this._rigCameras;
  21730. },
  21731. enumerable: true,
  21732. configurable: true
  21733. });
  21734. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  21735. get: function () {
  21736. return this._rigPostProcess;
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. /**
  21742. * Internal, gets the first post proces.
  21743. * @returns the first post process to be run on this camera.
  21744. */
  21745. Camera.prototype._getFirstPostProcess = function () {
  21746. for (var pp in this._postProcesses) {
  21747. if (this._postProcesses[pp] !== null) {
  21748. return this._postProcesses[pp];
  21749. }
  21750. }
  21751. return null;
  21752. };
  21753. Camera.prototype._cascadePostProcessesToRigCams = function () {
  21754. // invalidate framebuffer
  21755. var firstPostProcess = this._getFirstPostProcess();
  21756. if (firstPostProcess) {
  21757. firstPostProcess.markTextureDirty();
  21758. }
  21759. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  21760. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  21761. var cam = this._rigCameras[i];
  21762. var rigPostProcess = cam._rigPostProcess;
  21763. // for VR rig, there does not have to be a post process
  21764. if (rigPostProcess) {
  21765. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  21766. if (isPass) {
  21767. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  21768. cam.isIntermediate = this._postProcesses.length === 0;
  21769. }
  21770. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  21771. rigPostProcess.markTextureDirty();
  21772. }
  21773. else {
  21774. cam._postProcesses = this._postProcesses.slice(0);
  21775. }
  21776. }
  21777. };
  21778. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  21779. if (insertAt === void 0) { insertAt = null; }
  21780. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  21781. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  21782. return 0;
  21783. }
  21784. if (insertAt == null || insertAt < 0) {
  21785. this._postProcesses.push(postProcess);
  21786. }
  21787. else if (this._postProcesses[insertAt] === null) {
  21788. this._postProcesses[insertAt] = postProcess;
  21789. }
  21790. else {
  21791. this._postProcesses.splice(insertAt, 0, postProcess);
  21792. }
  21793. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21794. return this._postProcesses.indexOf(postProcess);
  21795. };
  21796. Camera.prototype.detachPostProcess = function (postProcess) {
  21797. var idx = this._postProcesses.indexOf(postProcess);
  21798. if (idx !== -1) {
  21799. this._postProcesses[idx] = null;
  21800. }
  21801. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21802. };
  21803. Camera.prototype.getWorldMatrix = function () {
  21804. if (!this._worldMatrix) {
  21805. this._worldMatrix = BABYLON.Matrix.Identity();
  21806. }
  21807. var viewMatrix = this.getViewMatrix();
  21808. viewMatrix.invertToRef(this._worldMatrix);
  21809. return this._worldMatrix;
  21810. };
  21811. Camera.prototype._getViewMatrix = function () {
  21812. return BABYLON.Matrix.Identity();
  21813. };
  21814. Camera.prototype.getViewMatrix = function (force) {
  21815. if (!force && this._isSynchronizedViewMatrix()) {
  21816. return this._computedViewMatrix;
  21817. }
  21818. this.updateCache();
  21819. this._computedViewMatrix = this._getViewMatrix();
  21820. this._currentRenderId = this.getScene().getRenderId();
  21821. this._childRenderId = this._currentRenderId;
  21822. this._refreshFrustumPlanes = true;
  21823. if (!this.parent || !this.parent.getWorldMatrix) {
  21824. this._globalPosition.copyFrom(this.position);
  21825. }
  21826. else {
  21827. if (!this._worldMatrix) {
  21828. this._worldMatrix = BABYLON.Matrix.Identity();
  21829. }
  21830. this._computedViewMatrix.invertToRef(this._worldMatrix);
  21831. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  21832. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  21833. this._computedViewMatrix.invert();
  21834. this._markSyncedWithParent();
  21835. }
  21836. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  21837. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  21838. }
  21839. this.onViewMatrixChangedObservable.notifyObservers(this);
  21840. return this._computedViewMatrix;
  21841. };
  21842. Camera.prototype.freezeProjectionMatrix = function (projection) {
  21843. this._doNotComputeProjectionMatrix = true;
  21844. if (projection !== undefined) {
  21845. this._projectionMatrix = projection;
  21846. }
  21847. };
  21848. ;
  21849. Camera.prototype.unfreezeProjectionMatrix = function () {
  21850. this._doNotComputeProjectionMatrix = false;
  21851. };
  21852. ;
  21853. Camera.prototype.getProjectionMatrix = function (force) {
  21854. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  21855. return this._projectionMatrix;
  21856. }
  21857. // Cache
  21858. this._cache.mode = this.mode;
  21859. this._cache.minZ = this.minZ;
  21860. this._cache.maxZ = this.maxZ;
  21861. // Matrix
  21862. this._refreshFrustumPlanes = true;
  21863. var engine = this.getEngine();
  21864. var scene = this.getScene();
  21865. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21866. this._cache.fov = this.fov;
  21867. this._cache.fovMode = this.fovMode;
  21868. this._cache.aspectRatio = engine.getAspectRatio(this);
  21869. if (this.minZ <= 0) {
  21870. this.minZ = 0.1;
  21871. }
  21872. if (scene.useRightHandedSystem) {
  21873. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21874. }
  21875. else {
  21876. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21877. }
  21878. }
  21879. else {
  21880. var halfWidth = engine.getRenderWidth() / 2.0;
  21881. var halfHeight = engine.getRenderHeight() / 2.0;
  21882. if (scene.useRightHandedSystem) {
  21883. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21884. }
  21885. else {
  21886. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21887. }
  21888. this._cache.orthoLeft = this.orthoLeft;
  21889. this._cache.orthoRight = this.orthoRight;
  21890. this._cache.orthoBottom = this.orthoBottom;
  21891. this._cache.orthoTop = this.orthoTop;
  21892. this._cache.renderWidth = engine.getRenderWidth();
  21893. this._cache.renderHeight = engine.getRenderHeight();
  21894. }
  21895. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  21896. return this._projectionMatrix;
  21897. };
  21898. Camera.prototype.getTranformationMatrix = function () {
  21899. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21900. return this._transformMatrix;
  21901. };
  21902. Camera.prototype.updateFrustumPlanes = function () {
  21903. if (!this._refreshFrustumPlanes) {
  21904. return;
  21905. }
  21906. this.getTranformationMatrix();
  21907. if (!this._frustumPlanes) {
  21908. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21909. }
  21910. else {
  21911. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21912. }
  21913. this._refreshFrustumPlanes = false;
  21914. };
  21915. Camera.prototype.isInFrustum = function (target) {
  21916. this.updateFrustumPlanes();
  21917. return target.isInFrustum(this._frustumPlanes);
  21918. };
  21919. Camera.prototype.isCompletelyInFrustum = function (target) {
  21920. this.updateFrustumPlanes();
  21921. return target.isCompletelyInFrustum(this._frustumPlanes);
  21922. };
  21923. Camera.prototype.getForwardRay = function (length, transform, origin) {
  21924. if (length === void 0) { length = 100; }
  21925. if (!transform) {
  21926. transform = this.getWorldMatrix();
  21927. }
  21928. if (!origin) {
  21929. origin = this.position;
  21930. }
  21931. var forward = new BABYLON.Vector3(0, 0, 1);
  21932. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  21933. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  21934. return new BABYLON.Ray(origin, direction, length);
  21935. };
  21936. /**
  21937. * Releases resources associated with this node.
  21938. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21939. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21940. */
  21941. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21942. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21943. // Observables
  21944. this.onViewMatrixChangedObservable.clear();
  21945. this.onProjectionMatrixChangedObservable.clear();
  21946. this.onAfterCheckInputsObservable.clear();
  21947. this.onRestoreStateObservable.clear();
  21948. // Inputs
  21949. if (this.inputs) {
  21950. this.inputs.clear();
  21951. }
  21952. // Animations
  21953. this.getScene().stopAnimation(this);
  21954. // Remove from scene
  21955. this.getScene().removeCamera(this);
  21956. while (this._rigCameras.length > 0) {
  21957. var camera = this._rigCameras.pop();
  21958. if (camera) {
  21959. camera.dispose();
  21960. }
  21961. }
  21962. // Postprocesses
  21963. if (this._rigPostProcess) {
  21964. this._rigPostProcess.dispose(this);
  21965. this._rigPostProcess = null;
  21966. this._postProcesses = [];
  21967. }
  21968. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21969. this._rigPostProcess = null;
  21970. this._postProcesses = [];
  21971. }
  21972. else {
  21973. var i = this._postProcesses.length;
  21974. while (--i >= 0) {
  21975. var postProcess = this._postProcesses[i];
  21976. if (postProcess) {
  21977. postProcess.dispose(this);
  21978. }
  21979. }
  21980. }
  21981. // Render targets
  21982. var i = this.customRenderTargets.length;
  21983. while (--i >= 0) {
  21984. this.customRenderTargets[i].dispose();
  21985. }
  21986. this.customRenderTargets = [];
  21987. // Active Meshes
  21988. this._activeMeshes.dispose();
  21989. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21990. };
  21991. Object.defineProperty(Camera.prototype, "leftCamera", {
  21992. // ---- Camera rigs section ----
  21993. get: function () {
  21994. if (this._rigCameras.length < 1) {
  21995. return null;
  21996. }
  21997. return this._rigCameras[0];
  21998. },
  21999. enumerable: true,
  22000. configurable: true
  22001. });
  22002. Object.defineProperty(Camera.prototype, "rightCamera", {
  22003. get: function () {
  22004. if (this._rigCameras.length < 2) {
  22005. return null;
  22006. }
  22007. return this._rigCameras[1];
  22008. },
  22009. enumerable: true,
  22010. configurable: true
  22011. });
  22012. Camera.prototype.getLeftTarget = function () {
  22013. if (this._rigCameras.length < 1) {
  22014. return null;
  22015. }
  22016. return this._rigCameras[0].getTarget();
  22017. };
  22018. Camera.prototype.getRightTarget = function () {
  22019. if (this._rigCameras.length < 2) {
  22020. return null;
  22021. }
  22022. return this._rigCameras[1].getTarget();
  22023. };
  22024. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22025. if (this.cameraRigMode === mode) {
  22026. return;
  22027. }
  22028. while (this._rigCameras.length > 0) {
  22029. var camera = this._rigCameras.pop();
  22030. if (camera) {
  22031. camera.dispose();
  22032. }
  22033. }
  22034. this.cameraRigMode = mode;
  22035. this._cameraRigParams = {};
  22036. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22037. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22038. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22039. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22040. // create the rig cameras, unless none
  22041. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22042. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22043. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22044. if (leftCamera && rightCamera) {
  22045. this._rigCameras.push(leftCamera);
  22046. this._rigCameras.push(rightCamera);
  22047. }
  22048. }
  22049. switch (this.cameraRigMode) {
  22050. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22051. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22052. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22053. break;
  22054. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22055. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22056. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22057. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22058. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22059. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22060. break;
  22061. case Camera.RIG_MODE_VR:
  22062. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22063. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22064. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22065. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22066. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22067. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22068. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22069. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22070. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22071. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22072. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22073. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22074. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22075. if (metrics.compensateDistortion) {
  22076. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22077. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22078. }
  22079. break;
  22080. case Camera.RIG_MODE_WEBVR:
  22081. if (rigParams.vrDisplay) {
  22082. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22083. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22084. //Left eye
  22085. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22086. this._rigCameras[0].setCameraRigParameter("left", true);
  22087. //leaving this for future reference
  22088. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22089. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22090. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22091. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22092. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22093. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22094. this._rigCameras[0].parent = this;
  22095. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22096. //Right eye
  22097. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22098. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22099. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22100. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22101. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22102. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22103. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22104. this._rigCameras[1].parent = this;
  22105. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22106. if (Camera.UseAlternateWebVRRendering) {
  22107. this._rigCameras[1]._skipRendering = true;
  22108. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22109. }
  22110. }
  22111. break;
  22112. }
  22113. this._cascadePostProcessesToRigCams();
  22114. this.update();
  22115. };
  22116. Camera.prototype._getVRProjectionMatrix = function () {
  22117. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22118. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22119. return this._projectionMatrix;
  22120. };
  22121. Camera.prototype._updateCameraRotationMatrix = function () {
  22122. //Here for WebVR
  22123. };
  22124. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22125. //Here for WebVR
  22126. };
  22127. /**
  22128. * This function MUST be overwritten by the different WebVR cameras available.
  22129. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22130. */
  22131. Camera.prototype._getWebVRProjectionMatrix = function () {
  22132. return BABYLON.Matrix.Identity();
  22133. };
  22134. /**
  22135. * This function MUST be overwritten by the different WebVR cameras available.
  22136. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22137. */
  22138. Camera.prototype._getWebVRViewMatrix = function () {
  22139. return BABYLON.Matrix.Identity();
  22140. };
  22141. Camera.prototype.setCameraRigParameter = function (name, value) {
  22142. if (!this._cameraRigParams) {
  22143. this._cameraRigParams = {};
  22144. }
  22145. this._cameraRigParams[name] = value;
  22146. //provisionnally:
  22147. if (name === "interaxialDistance") {
  22148. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22149. }
  22150. };
  22151. /**
  22152. * needs to be overridden by children so sub has required properties to be copied
  22153. */
  22154. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22155. return null;
  22156. };
  22157. /**
  22158. * May need to be overridden by children
  22159. */
  22160. Camera.prototype._updateRigCameras = function () {
  22161. for (var i = 0; i < this._rigCameras.length; i++) {
  22162. this._rigCameras[i].minZ = this.minZ;
  22163. this._rigCameras[i].maxZ = this.maxZ;
  22164. this._rigCameras[i].fov = this.fov;
  22165. }
  22166. // only update viewport when ANAGLYPH
  22167. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22168. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22169. }
  22170. };
  22171. Camera.prototype._setupInputs = function () {
  22172. };
  22173. Camera.prototype.serialize = function () {
  22174. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22175. // Type
  22176. serializationObject.type = this.getClassName();
  22177. // Parent
  22178. if (this.parent) {
  22179. serializationObject.parentId = this.parent.id;
  22180. }
  22181. if (this.inputs) {
  22182. this.inputs.serialize(serializationObject);
  22183. }
  22184. // Animations
  22185. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22186. serializationObject.ranges = this.serializeAnimationRanges();
  22187. return serializationObject;
  22188. };
  22189. Camera.prototype.clone = function (name) {
  22190. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22191. };
  22192. Camera.prototype.getDirection = function (localAxis) {
  22193. var result = BABYLON.Vector3.Zero();
  22194. this.getDirectionToRef(localAxis, result);
  22195. return result;
  22196. };
  22197. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22198. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22199. };
  22200. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22201. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22202. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22203. switch (type) {
  22204. case "ArcRotateCamera":
  22205. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22206. case "DeviceOrientationCamera":
  22207. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22208. case "FollowCamera":
  22209. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22210. case "ArcFollowCamera":
  22211. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22212. case "GamepadCamera":
  22213. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22214. case "TouchCamera":
  22215. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22216. case "VirtualJoysticksCamera":
  22217. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22218. case "WebVRFreeCamera":
  22219. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22220. case "WebVRGamepadCamera":
  22221. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22222. case "VRDeviceOrientationFreeCamera":
  22223. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22224. case "VRDeviceOrientationGamepadCamera":
  22225. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22226. case "AnaglyphArcRotateCamera":
  22227. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22228. case "AnaglyphFreeCamera":
  22229. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22230. case "AnaglyphGamepadCamera":
  22231. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22232. case "AnaglyphUniversalCamera":
  22233. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22234. case "StereoscopicArcRotateCamera":
  22235. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22236. case "StereoscopicFreeCamera":
  22237. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22238. case "StereoscopicGamepadCamera":
  22239. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22240. case "StereoscopicUniversalCamera":
  22241. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22242. case "FreeCamera":// Forcing Universal here
  22243. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22244. default:// Universal Camera is the default value
  22245. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22246. }
  22247. };
  22248. Camera.prototype.computeWorldMatrix = function () {
  22249. return this.getWorldMatrix();
  22250. };
  22251. Camera.Parse = function (parsedCamera, scene) {
  22252. var type = parsedCamera.type;
  22253. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22254. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22255. // Parent
  22256. if (parsedCamera.parentId) {
  22257. camera._waitingParentId = parsedCamera.parentId;
  22258. }
  22259. //If camera has an input manager, let it parse inputs settings
  22260. if (camera.inputs) {
  22261. camera.inputs.parse(parsedCamera);
  22262. camera._setupInputs();
  22263. }
  22264. if (camera.setPosition) {
  22265. camera.position.copyFromFloats(0, 0, 0);
  22266. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22267. }
  22268. // Target
  22269. if (parsedCamera.target) {
  22270. if (camera.setTarget) {
  22271. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22272. }
  22273. }
  22274. // Apply 3d rig, when found
  22275. if (parsedCamera.cameraRigMode) {
  22276. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22277. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22278. }
  22279. // Animations
  22280. if (parsedCamera.animations) {
  22281. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22282. var parsedAnimation = parsedCamera.animations[animationIndex];
  22283. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22284. }
  22285. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22286. }
  22287. if (parsedCamera.autoAnimate) {
  22288. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22289. }
  22290. return camera;
  22291. };
  22292. // Statics
  22293. Camera._PERSPECTIVE_CAMERA = 0;
  22294. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22295. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22296. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22297. Camera._RIG_MODE_NONE = 0;
  22298. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22299. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22300. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22301. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22302. Camera._RIG_MODE_VR = 20;
  22303. Camera._RIG_MODE_WEBVR = 21;
  22304. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22305. Camera.UseAlternateWebVRRendering = false;
  22306. __decorate([
  22307. BABYLON.serializeAsVector3()
  22308. ], Camera.prototype, "position", void 0);
  22309. __decorate([
  22310. BABYLON.serializeAsVector3()
  22311. ], Camera.prototype, "upVector", void 0);
  22312. __decorate([
  22313. BABYLON.serialize()
  22314. ], Camera.prototype, "orthoLeft", void 0);
  22315. __decorate([
  22316. BABYLON.serialize()
  22317. ], Camera.prototype, "orthoRight", void 0);
  22318. __decorate([
  22319. BABYLON.serialize()
  22320. ], Camera.prototype, "orthoBottom", void 0);
  22321. __decorate([
  22322. BABYLON.serialize()
  22323. ], Camera.prototype, "orthoTop", void 0);
  22324. __decorate([
  22325. BABYLON.serialize()
  22326. ], Camera.prototype, "fov", void 0);
  22327. __decorate([
  22328. BABYLON.serialize()
  22329. ], Camera.prototype, "minZ", void 0);
  22330. __decorate([
  22331. BABYLON.serialize()
  22332. ], Camera.prototype, "maxZ", void 0);
  22333. __decorate([
  22334. BABYLON.serialize()
  22335. ], Camera.prototype, "inertia", void 0);
  22336. __decorate([
  22337. BABYLON.serialize()
  22338. ], Camera.prototype, "mode", void 0);
  22339. __decorate([
  22340. BABYLON.serialize()
  22341. ], Camera.prototype, "layerMask", void 0);
  22342. __decorate([
  22343. BABYLON.serialize()
  22344. ], Camera.prototype, "fovMode", void 0);
  22345. __decorate([
  22346. BABYLON.serialize()
  22347. ], Camera.prototype, "cameraRigMode", void 0);
  22348. __decorate([
  22349. BABYLON.serialize()
  22350. ], Camera.prototype, "interaxialDistance", void 0);
  22351. __decorate([
  22352. BABYLON.serialize()
  22353. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22354. return Camera;
  22355. }(BABYLON.Node));
  22356. BABYLON.Camera = Camera;
  22357. })(BABYLON || (BABYLON = {}));
  22358. //# sourceMappingURL=babylon.camera.js.map
  22359. "use strict";
  22360. var BABYLON;
  22361. (function (BABYLON) {
  22362. var RenderingManager = /** @class */ (function () {
  22363. function RenderingManager(scene) {
  22364. this._renderingGroups = new Array();
  22365. this._autoClearDepthStencil = {};
  22366. this._customOpaqueSortCompareFn = {};
  22367. this._customAlphaTestSortCompareFn = {};
  22368. this._customTransparentSortCompareFn = {};
  22369. this._renderinGroupInfo = null;
  22370. this._scene = scene;
  22371. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22372. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22373. }
  22374. }
  22375. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22376. if (depth === void 0) { depth = true; }
  22377. if (stencil === void 0) { stencil = true; }
  22378. if (this._depthStencilBufferAlreadyCleaned) {
  22379. return;
  22380. }
  22381. this._scene.getEngine().clear(null, false, depth, stencil);
  22382. this._depthStencilBufferAlreadyCleaned = true;
  22383. };
  22384. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22385. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22386. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22387. var info = null;
  22388. if (observable) {
  22389. if (!this._renderinGroupInfo) {
  22390. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22391. }
  22392. info = this._renderinGroupInfo;
  22393. info.scene = this._scene;
  22394. info.camera = this._scene.activeCamera;
  22395. }
  22396. // Dispatch sprites
  22397. if (renderSprites) {
  22398. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22399. var manager = this._scene.spriteManagers[index];
  22400. this.dispatchSprites(manager);
  22401. }
  22402. }
  22403. // Render
  22404. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22405. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22406. var renderingGroup = this._renderingGroups[index];
  22407. if (!renderingGroup && !observable)
  22408. continue;
  22409. var renderingGroupMask = 0;
  22410. // Fire PRECLEAR stage
  22411. if (observable && info) {
  22412. renderingGroupMask = Math.pow(2, index);
  22413. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22414. info.renderingGroupId = index;
  22415. observable.notifyObservers(info, renderingGroupMask);
  22416. }
  22417. // Clear depth/stencil if needed
  22418. if (RenderingManager.AUTOCLEAR) {
  22419. var autoClear = this._autoClearDepthStencil[index];
  22420. if (autoClear && autoClear.autoClear) {
  22421. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22422. }
  22423. }
  22424. if (observable && info) {
  22425. // Fire PREOPAQUE stage
  22426. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22427. observable.notifyObservers(info, renderingGroupMask);
  22428. // Fire PRETRANSPARENT stage
  22429. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22430. observable.notifyObservers(info, renderingGroupMask);
  22431. }
  22432. if (renderingGroup)
  22433. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22434. // Fire POSTTRANSPARENT stage
  22435. if (observable && info) {
  22436. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22437. observable.notifyObservers(info, renderingGroupMask);
  22438. }
  22439. }
  22440. };
  22441. RenderingManager.prototype.reset = function () {
  22442. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22443. var renderingGroup = this._renderingGroups[index];
  22444. if (renderingGroup) {
  22445. renderingGroup.prepare();
  22446. }
  22447. }
  22448. };
  22449. RenderingManager.prototype.dispose = function () {
  22450. this.freeRenderingGroups();
  22451. this._renderingGroups.length = 0;
  22452. };
  22453. /**
  22454. * Clear the info related to rendering groups preventing retention points during dispose.
  22455. */
  22456. RenderingManager.prototype.freeRenderingGroups = function () {
  22457. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22458. var renderingGroup = this._renderingGroups[index];
  22459. if (renderingGroup) {
  22460. renderingGroup.dispose();
  22461. }
  22462. }
  22463. };
  22464. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22465. if (this._renderingGroups[renderingGroupId] === undefined) {
  22466. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22467. }
  22468. };
  22469. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22470. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22471. this._prepareRenderingGroup(renderingGroupId);
  22472. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22473. };
  22474. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22475. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22476. this._prepareRenderingGroup(renderingGroupId);
  22477. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22478. };
  22479. /**
  22480. * @param subMesh The submesh to dispatch
  22481. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22482. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22483. */
  22484. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22485. if (mesh === undefined) {
  22486. mesh = subMesh.getMesh();
  22487. }
  22488. var renderingGroupId = mesh.renderingGroupId || 0;
  22489. this._prepareRenderingGroup(renderingGroupId);
  22490. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22491. };
  22492. /**
  22493. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22494. * This allowed control for front to back rendering or reversly depending of the special needs.
  22495. *
  22496. * @param renderingGroupId The rendering group id corresponding to its index
  22497. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22498. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22499. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22500. */
  22501. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22502. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22503. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22504. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22505. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22506. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22507. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22508. if (this._renderingGroups[renderingGroupId]) {
  22509. var group = this._renderingGroups[renderingGroupId];
  22510. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22511. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22512. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22513. }
  22514. };
  22515. /**
  22516. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22517. *
  22518. * @param renderingGroupId The rendering group id corresponding to its index
  22519. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22520. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22521. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22522. */
  22523. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22524. if (depth === void 0) { depth = true; }
  22525. if (stencil === void 0) { stencil = true; }
  22526. this._autoClearDepthStencil[renderingGroupId] = {
  22527. autoClear: autoClearDepthStencil,
  22528. depth: depth,
  22529. stencil: stencil
  22530. };
  22531. };
  22532. /**
  22533. * The max id used for rendering groups (not included)
  22534. */
  22535. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22536. /**
  22537. * The min id used for rendering groups (included)
  22538. */
  22539. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22540. /**
  22541. * Used to globally prevent autoclearing scenes.
  22542. */
  22543. RenderingManager.AUTOCLEAR = true;
  22544. return RenderingManager;
  22545. }());
  22546. BABYLON.RenderingManager = RenderingManager;
  22547. })(BABYLON || (BABYLON = {}));
  22548. //# sourceMappingURL=babylon.renderingManager.js.map
  22549. "use strict";
  22550. var BABYLON;
  22551. (function (BABYLON) {
  22552. var RenderingGroup = /** @class */ (function () {
  22553. /**
  22554. * Creates a new rendering group.
  22555. * @param index The rendering group index
  22556. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22557. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22558. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22559. */
  22560. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22561. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22562. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22563. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22564. this.index = index;
  22565. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22566. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22567. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22568. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22569. this._particleSystems = new BABYLON.SmartArray(256);
  22570. this._spriteManagers = new BABYLON.SmartArray(256);
  22571. this._edgesRenderers = new BABYLON.SmartArray(16);
  22572. this._scene = scene;
  22573. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22574. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22575. this.transparentSortCompareFn = transparentSortCompareFn;
  22576. }
  22577. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22578. /**
  22579. * Set the opaque sort comparison function.
  22580. * If null the sub meshes will be render in the order they were created
  22581. */
  22582. set: function (value) {
  22583. this._opaqueSortCompareFn = value;
  22584. if (value) {
  22585. this._renderOpaque = this.renderOpaqueSorted;
  22586. }
  22587. else {
  22588. this._renderOpaque = RenderingGroup.renderUnsorted;
  22589. }
  22590. },
  22591. enumerable: true,
  22592. configurable: true
  22593. });
  22594. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22595. /**
  22596. * Set the alpha test sort comparison function.
  22597. * If null the sub meshes will be render in the order they were created
  22598. */
  22599. set: function (value) {
  22600. this._alphaTestSortCompareFn = value;
  22601. if (value) {
  22602. this._renderAlphaTest = this.renderAlphaTestSorted;
  22603. }
  22604. else {
  22605. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22606. }
  22607. },
  22608. enumerable: true,
  22609. configurable: true
  22610. });
  22611. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22612. /**
  22613. * Set the transparent sort comparison function.
  22614. * If null the sub meshes will be render in the order they were created
  22615. */
  22616. set: function (value) {
  22617. if (value) {
  22618. this._transparentSortCompareFn = value;
  22619. }
  22620. else {
  22621. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22622. }
  22623. this._renderTransparent = this.renderTransparentSorted;
  22624. },
  22625. enumerable: true,
  22626. configurable: true
  22627. });
  22628. /**
  22629. * Render all the sub meshes contained in the group.
  22630. * @param customRenderFunction Used to override the default render behaviour of the group.
  22631. * @returns true if rendered some submeshes.
  22632. */
  22633. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22634. if (customRenderFunction) {
  22635. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22636. return;
  22637. }
  22638. var engine = this._scene.getEngine();
  22639. // Depth only
  22640. if (this._depthOnlySubMeshes.length !== 0) {
  22641. engine.setColorWrite(false);
  22642. this._renderAlphaTest(this._depthOnlySubMeshes);
  22643. engine.setColorWrite(true);
  22644. }
  22645. // Opaque
  22646. if (this._opaqueSubMeshes.length !== 0) {
  22647. this._renderOpaque(this._opaqueSubMeshes);
  22648. }
  22649. // Alpha test
  22650. if (this._alphaTestSubMeshes.length !== 0) {
  22651. this._renderAlphaTest(this._alphaTestSubMeshes);
  22652. }
  22653. var stencilState = engine.getStencilBuffer();
  22654. engine.setStencilBuffer(false);
  22655. // Sprites
  22656. if (renderSprites) {
  22657. this._renderSprites();
  22658. }
  22659. // Particles
  22660. if (renderParticles) {
  22661. this._renderParticles(activeMeshes);
  22662. }
  22663. if (this.onBeforeTransparentRendering) {
  22664. this.onBeforeTransparentRendering();
  22665. }
  22666. // Transparent
  22667. if (this._transparentSubMeshes.length !== 0) {
  22668. this._renderTransparent(this._transparentSubMeshes);
  22669. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22670. }
  22671. // Set back stencil to false in case it changes before the edge renderer.
  22672. engine.setStencilBuffer(false);
  22673. // Edges
  22674. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22675. this._edgesRenderers.data[edgesRendererIndex].render();
  22676. }
  22677. // Restore Stencil state.
  22678. engine.setStencilBuffer(stencilState);
  22679. };
  22680. /**
  22681. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  22682. * @param subMeshes The submeshes to render
  22683. */
  22684. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  22685. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  22686. };
  22687. /**
  22688. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  22689. * @param subMeshes The submeshes to render
  22690. */
  22691. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  22692. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  22693. };
  22694. /**
  22695. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  22696. * @param subMeshes The submeshes to render
  22697. */
  22698. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  22699. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  22700. };
  22701. /**
  22702. * Renders the submeshes in a specified order.
  22703. * @param subMeshes The submeshes to sort before render
  22704. * @param sortCompareFn The comparison function use to sort
  22705. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  22706. * @param transparent Specifies to activate blending if true
  22707. */
  22708. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  22709. var subIndex = 0;
  22710. var subMesh;
  22711. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  22712. for (; subIndex < subMeshes.length; subIndex++) {
  22713. subMesh = subMeshes.data[subIndex];
  22714. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  22715. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  22716. }
  22717. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  22718. if (sortCompareFn) {
  22719. sortedArray.sort(sortCompareFn);
  22720. }
  22721. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  22722. subMesh = sortedArray[subIndex];
  22723. if (transparent) {
  22724. var material = subMesh.getMaterial();
  22725. if (material && material.needDepthPrePass) {
  22726. var engine = material.getScene().getEngine();
  22727. engine.setColorWrite(false);
  22728. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22729. subMesh.render(false);
  22730. engine.setColorWrite(true);
  22731. }
  22732. }
  22733. subMesh.render(transparent);
  22734. }
  22735. };
  22736. /**
  22737. * Renders the submeshes in the order they were dispatched (no sort applied).
  22738. * @param subMeshes The submeshes to render
  22739. */
  22740. RenderingGroup.renderUnsorted = function (subMeshes) {
  22741. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  22742. var submesh = subMeshes.data[subIndex];
  22743. submesh.render(false);
  22744. }
  22745. };
  22746. /**
  22747. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22748. * are rendered back to front if in the same alpha index.
  22749. *
  22750. * @param a The first submesh
  22751. * @param b The second submesh
  22752. * @returns The result of the comparison
  22753. */
  22754. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  22755. // Alpha index first
  22756. if (a._alphaIndex > b._alphaIndex) {
  22757. return 1;
  22758. }
  22759. if (a._alphaIndex < b._alphaIndex) {
  22760. return -1;
  22761. }
  22762. // Then distance to camera
  22763. return RenderingGroup.backToFrontSortCompare(a, b);
  22764. };
  22765. /**
  22766. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22767. * are rendered back to front.
  22768. *
  22769. * @param a The first submesh
  22770. * @param b The second submesh
  22771. * @returns The result of the comparison
  22772. */
  22773. RenderingGroup.backToFrontSortCompare = function (a, b) {
  22774. // Then distance to camera
  22775. if (a._distanceToCamera < b._distanceToCamera) {
  22776. return 1;
  22777. }
  22778. if (a._distanceToCamera > b._distanceToCamera) {
  22779. return -1;
  22780. }
  22781. return 0;
  22782. };
  22783. /**
  22784. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22785. * are rendered front to back (prevent overdraw).
  22786. *
  22787. * @param a The first submesh
  22788. * @param b The second submesh
  22789. * @returns The result of the comparison
  22790. */
  22791. RenderingGroup.frontToBackSortCompare = function (a, b) {
  22792. // Then distance to camera
  22793. if (a._distanceToCamera < b._distanceToCamera) {
  22794. return -1;
  22795. }
  22796. if (a._distanceToCamera > b._distanceToCamera) {
  22797. return 1;
  22798. }
  22799. return 0;
  22800. };
  22801. /**
  22802. * Resets the different lists of submeshes to prepare a new frame.
  22803. */
  22804. RenderingGroup.prototype.prepare = function () {
  22805. this._opaqueSubMeshes.reset();
  22806. this._transparentSubMeshes.reset();
  22807. this._alphaTestSubMeshes.reset();
  22808. this._depthOnlySubMeshes.reset();
  22809. this._particleSystems.reset();
  22810. this._spriteManagers.reset();
  22811. this._edgesRenderers.reset();
  22812. };
  22813. RenderingGroup.prototype.dispose = function () {
  22814. this._opaqueSubMeshes.dispose();
  22815. this._transparentSubMeshes.dispose();
  22816. this._alphaTestSubMeshes.dispose();
  22817. this._depthOnlySubMeshes.dispose();
  22818. this._particleSystems.dispose();
  22819. this._spriteManagers.dispose();
  22820. this._edgesRenderers.dispose();
  22821. };
  22822. /**
  22823. * Inserts the submesh in its correct queue depending on its material.
  22824. * @param subMesh The submesh to dispatch
  22825. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22826. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22827. */
  22828. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  22829. // Get mesh and materials if not provided
  22830. if (mesh === undefined) {
  22831. mesh = subMesh.getMesh();
  22832. }
  22833. if (material === undefined) {
  22834. material = subMesh.getMaterial();
  22835. }
  22836. if (material === null || material === undefined) {
  22837. return;
  22838. }
  22839. if (material.needAlphaBlendingForMesh(mesh)) {
  22840. this._transparentSubMeshes.push(subMesh);
  22841. }
  22842. else if (material.needAlphaTesting()) {
  22843. if (material.needDepthPrePass) {
  22844. this._depthOnlySubMeshes.push(subMesh);
  22845. }
  22846. this._alphaTestSubMeshes.push(subMesh);
  22847. }
  22848. else {
  22849. if (material.needDepthPrePass) {
  22850. this._depthOnlySubMeshes.push(subMesh);
  22851. }
  22852. this._opaqueSubMeshes.push(subMesh); // Opaque
  22853. }
  22854. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  22855. this._edgesRenderers.push(mesh._edgesRenderer);
  22856. }
  22857. };
  22858. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  22859. this._spriteManagers.push(spriteManager);
  22860. };
  22861. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  22862. this._particleSystems.push(particleSystem);
  22863. };
  22864. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  22865. if (this._particleSystems.length === 0) {
  22866. return;
  22867. }
  22868. // Particles
  22869. var activeCamera = this._scene.activeCamera;
  22870. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  22871. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  22872. var particleSystem = this._particleSystems.data[particleIndex];
  22873. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  22874. continue;
  22875. }
  22876. var emitter = particleSystem.emitter;
  22877. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  22878. this._scene._activeParticles.addCount(particleSystem.render(), false);
  22879. }
  22880. }
  22881. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  22882. };
  22883. RenderingGroup.prototype._renderSprites = function () {
  22884. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  22885. return;
  22886. }
  22887. // Sprites
  22888. var activeCamera = this._scene.activeCamera;
  22889. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  22890. for (var id = 0; id < this._spriteManagers.length; id++) {
  22891. var spriteManager = this._spriteManagers.data[id];
  22892. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  22893. spriteManager.render();
  22894. }
  22895. }
  22896. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  22897. };
  22898. return RenderingGroup;
  22899. }());
  22900. BABYLON.RenderingGroup = RenderingGroup;
  22901. })(BABYLON || (BABYLON = {}));
  22902. //# sourceMappingURL=babylon.renderingGroup.js.map
  22903. "use strict";
  22904. var BABYLON;
  22905. (function (BABYLON) {
  22906. /** @ignore */
  22907. var ClickInfo = /** @class */ (function () {
  22908. function ClickInfo() {
  22909. this._singleClick = false;
  22910. this._doubleClick = false;
  22911. this._hasSwiped = false;
  22912. this._ignore = false;
  22913. }
  22914. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  22915. get: function () {
  22916. return this._singleClick;
  22917. },
  22918. set: function (b) {
  22919. this._singleClick = b;
  22920. },
  22921. enumerable: true,
  22922. configurable: true
  22923. });
  22924. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  22925. get: function () {
  22926. return this._doubleClick;
  22927. },
  22928. set: function (b) {
  22929. this._doubleClick = b;
  22930. },
  22931. enumerable: true,
  22932. configurable: true
  22933. });
  22934. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  22935. get: function () {
  22936. return this._hasSwiped;
  22937. },
  22938. set: function (b) {
  22939. this._hasSwiped = b;
  22940. },
  22941. enumerable: true,
  22942. configurable: true
  22943. });
  22944. Object.defineProperty(ClickInfo.prototype, "ignore", {
  22945. get: function () {
  22946. return this._ignore;
  22947. },
  22948. set: function (b) {
  22949. this._ignore = b;
  22950. },
  22951. enumerable: true,
  22952. configurable: true
  22953. });
  22954. return ClickInfo;
  22955. }());
  22956. /**
  22957. * This class is used by the onRenderingGroupObservable
  22958. */
  22959. var RenderingGroupInfo = /** @class */ (function () {
  22960. function RenderingGroupInfo() {
  22961. }
  22962. /**
  22963. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  22964. * This stage will be fired no matter what
  22965. */
  22966. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  22967. /**
  22968. * Called before opaque object are rendered.
  22969. * This stage will be fired only if there's 3D Opaque content to render
  22970. */
  22971. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  22972. /**
  22973. * Called after the opaque objects are rendered and before the transparent ones
  22974. * This stage will be fired only if there's 3D transparent content to render
  22975. */
  22976. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  22977. /**
  22978. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  22979. * This stage will be fired no matter what
  22980. */
  22981. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  22982. return RenderingGroupInfo;
  22983. }());
  22984. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  22985. /**
  22986. * Represents a scene to be rendered by the engine.
  22987. * @see http://doc.babylonjs.com/features/scene
  22988. */
  22989. var Scene = /** @class */ (function () {
  22990. /**
  22991. * Creates a new Scene
  22992. * @param engine defines the engine to use to render this scene
  22993. */
  22994. function Scene(engine) {
  22995. // Members
  22996. /**
  22997. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  22998. */
  22999. this.autoClear = true;
  23000. /**
  23001. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23002. */
  23003. this.autoClearDepthAndStencil = true;
  23004. /**
  23005. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23006. */
  23007. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23008. /**
  23009. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23010. */
  23011. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23012. this._forceWireframe = false;
  23013. this._forcePointsCloud = false;
  23014. /**
  23015. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23016. */
  23017. this.forceShowBoundingBoxes = false;
  23018. /**
  23019. * Gets or sets a boolean indicating if animations are enabled
  23020. */
  23021. this.animationsEnabled = true;
  23022. /**
  23023. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23024. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23025. */
  23026. this.useConstantAnimationDeltaTime = false;
  23027. /**
  23028. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23029. * Please note that it requires to run a ray cast through the scene on every frame
  23030. */
  23031. this.constantlyUpdateMeshUnderPointer = false;
  23032. /**
  23033. * Defines the HTML cursor to use when hovering over interactive elements
  23034. */
  23035. this.hoverCursor = "pointer";
  23036. /**
  23037. * Defines the HTML default cursor to use (empty by default)
  23038. */
  23039. this.defaultCursor = "";
  23040. /**
  23041. * This is used to call preventDefault() on pointer down
  23042. * in order to block unwanted artifacts like system double clicks
  23043. */
  23044. this.preventDefaultOnPointerDown = true;
  23045. // Metadata
  23046. /**
  23047. * Gets or sets user defined metadata
  23048. */
  23049. this.metadata = null;
  23050. /**
  23051. * Use this array to add regular expressions used to disable offline support for specific urls
  23052. */
  23053. this.disableOfflineSupportExceptionRules = new Array();
  23054. /**
  23055. * An event triggered when the scene is disposed.
  23056. */
  23057. this.onDisposeObservable = new BABYLON.Observable();
  23058. this._onDisposeObserver = null;
  23059. /**
  23060. * An event triggered before rendering the scene (right after animations and physics)
  23061. */
  23062. this.onBeforeRenderObservable = new BABYLON.Observable();
  23063. this._onBeforeRenderObserver = null;
  23064. /**
  23065. * An event triggered after rendering the scene
  23066. */
  23067. this.onAfterRenderObservable = new BABYLON.Observable();
  23068. this._onAfterRenderObserver = null;
  23069. /**
  23070. * An event triggered before animating the scene
  23071. */
  23072. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23073. /**
  23074. * An event triggered after animations processing
  23075. */
  23076. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23077. /**
  23078. * An event triggered before draw calls are ready to be sent
  23079. */
  23080. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23081. /**
  23082. * An event triggered after draw calls have been sent
  23083. */
  23084. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23085. /**
  23086. * An event triggered when physic simulation is about to be run
  23087. */
  23088. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23089. /**
  23090. * An event triggered when physic simulation has been done
  23091. */
  23092. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23093. /**
  23094. * An event triggered when the scene is ready
  23095. */
  23096. this.onReadyObservable = new BABYLON.Observable();
  23097. /**
  23098. * An event triggered before rendering a camera
  23099. */
  23100. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23101. this._onBeforeCameraRenderObserver = null;
  23102. /**
  23103. * An event triggered after rendering a camera
  23104. */
  23105. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23106. this._onAfterCameraRenderObserver = null;
  23107. /**
  23108. * An event triggered when active meshes evaluation is about to start
  23109. */
  23110. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23111. /**
  23112. * An event triggered when active meshes evaluation is done
  23113. */
  23114. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23115. /**
  23116. * An event triggered when particles rendering is about to start
  23117. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23118. */
  23119. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23120. /**
  23121. * An event triggered when particles rendering is done
  23122. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23123. */
  23124. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23125. /**
  23126. * An event triggered when sprites rendering is about to start
  23127. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23128. */
  23129. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23130. /**
  23131. * An event triggered when sprites rendering is done
  23132. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23133. */
  23134. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23135. /**
  23136. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23137. */
  23138. this.onDataLoadedObservable = new BABYLON.Observable();
  23139. /**
  23140. * An event triggered when a camera is created
  23141. */
  23142. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23143. /**
  23144. * An event triggered when a camera is removed
  23145. */
  23146. this.onCameraRemovedObservable = new BABYLON.Observable();
  23147. /**
  23148. * An event triggered when a light is created
  23149. */
  23150. this.onNewLightAddedObservable = new BABYLON.Observable();
  23151. /**
  23152. * An event triggered when a light is removed
  23153. */
  23154. this.onLightRemovedObservable = new BABYLON.Observable();
  23155. /**
  23156. * An event triggered when a geometry is created
  23157. */
  23158. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23159. /**
  23160. * An event triggered when a geometry is removed
  23161. */
  23162. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23163. /**
  23164. * An event triggered when a transform node is created
  23165. */
  23166. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23167. /**
  23168. * An event triggered when a transform node is removed
  23169. */
  23170. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23171. /**
  23172. * An event triggered when a mesh is created
  23173. */
  23174. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23175. /**
  23176. * An event triggered when a mesh is removed
  23177. */
  23178. this.onMeshRemovedObservable = new BABYLON.Observable();
  23179. /**
  23180. * An event triggered when render targets are about to be rendered
  23181. * Can happen multiple times per frame.
  23182. */
  23183. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23184. /**
  23185. * An event triggered when render targets were rendered.
  23186. * Can happen multiple times per frame.
  23187. */
  23188. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23189. /**
  23190. * An event triggered before calculating deterministic simulation step
  23191. */
  23192. this.onBeforeStepObservable = new BABYLON.Observable();
  23193. /**
  23194. * An event triggered after calculating deterministic simulation step
  23195. */
  23196. this.onAfterStepObservable = new BABYLON.Observable();
  23197. /**
  23198. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23199. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23200. * 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)
  23201. */
  23202. this.onRenderingGroupObservable = new BABYLON.Observable();
  23203. // Animations
  23204. /**
  23205. * Gets a list of Animations associated with the scene
  23206. */
  23207. this.animations = [];
  23208. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23209. /**
  23210. * 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).
  23211. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23212. */
  23213. this.onPrePointerObservable = new BABYLON.Observable();
  23214. /**
  23215. * Observable event triggered each time an input event is received from the rendering canvas
  23216. */
  23217. this.onPointerObservable = new BABYLON.Observable();
  23218. this._meshPickProceed = false;
  23219. this._currentPickResult = null;
  23220. this._previousPickResult = null;
  23221. this._totalPointersPressed = 0;
  23222. this._doubleClickOccured = false;
  23223. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23224. this.cameraToUseForPointers = null;
  23225. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23226. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23227. this._startingPointerTime = 0;
  23228. this._previousStartingPointerTime = 0;
  23229. // Deterministic lockstep
  23230. this._timeAccumulator = 0;
  23231. this._currentStepId = 0;
  23232. this._currentInternalStep = 0;
  23233. // Keyboard
  23234. /**
  23235. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23236. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23237. */
  23238. this.onPreKeyboardObservable = new BABYLON.Observable();
  23239. /**
  23240. * Observable event triggered each time an keyboard event is received from the hosting window
  23241. */
  23242. this.onKeyboardObservable = new BABYLON.Observable();
  23243. // Coordinates system
  23244. this._useRightHandedSystem = false;
  23245. // Fog
  23246. this._fogEnabled = true;
  23247. this._fogMode = Scene.FOGMODE_NONE;
  23248. /**
  23249. * Gets or sets the fog color to use
  23250. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23251. */
  23252. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23253. /**
  23254. * Gets or sets the fog density to use
  23255. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23256. */
  23257. this.fogDensity = 0.1;
  23258. /**
  23259. * Gets or sets the fog start distance to use
  23260. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23261. */
  23262. this.fogStart = 0;
  23263. /**
  23264. * Gets or sets the fog end distance to use
  23265. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23266. */
  23267. this.fogEnd = 1000.0;
  23268. // Lights
  23269. this._shadowsEnabled = true;
  23270. this._lightsEnabled = true;
  23271. /**
  23272. * All of the lights added to this scene
  23273. * @see http://doc.babylonjs.com/babylon101/lights
  23274. */
  23275. this.lights = new Array();
  23276. // Cameras
  23277. /** All of the cameras added to this scene.
  23278. * @see http://doc.babylonjs.com/babylon101/cameras
  23279. */
  23280. this.cameras = new Array();
  23281. /** All of the active cameras added to this scene. */
  23282. this.activeCameras = new Array();
  23283. // Meshes
  23284. /**
  23285. * All of the tranform nodes added to this scene
  23286. * @see http://doc.babylonjs.com/how_to/transformnode
  23287. */
  23288. this.transformNodes = new Array();
  23289. /**
  23290. * All of the (abstract) meshes added to this scene
  23291. */
  23292. this.meshes = new Array();
  23293. /**
  23294. * All of the animation groups added to this scene
  23295. * @see http://doc.babylonjs.com/how_to/group
  23296. */
  23297. this.animationGroups = new Array();
  23298. // Geometries
  23299. this._geometries = new Array();
  23300. /**
  23301. * All of the materials added to this scene
  23302. * @see http://doc.babylonjs.com/babylon101/materials
  23303. */
  23304. this.materials = new Array();
  23305. /**
  23306. * All of the multi-materials added to this scene
  23307. * @see http://doc.babylonjs.com/how_to/multi_materials
  23308. */
  23309. this.multiMaterials = new Array();
  23310. // Textures
  23311. this._texturesEnabled = true;
  23312. /**
  23313. * All of the textures added to this scene
  23314. */
  23315. this.textures = new Array();
  23316. // Particles
  23317. /**
  23318. * Gets or sets a boolean indicating if particles are enabled on this scene
  23319. */
  23320. this.particlesEnabled = true;
  23321. /**
  23322. * All of the particle systems added to this scene
  23323. * @see http://doc.babylonjs.com/babylon101/particles
  23324. */
  23325. this.particleSystems = new Array();
  23326. // Sprites
  23327. /**
  23328. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23329. */
  23330. this.spritesEnabled = true;
  23331. /**
  23332. * All of the sprite managers added to this scene
  23333. * @see http://doc.babylonjs.com/babylon101/sprites
  23334. */
  23335. this.spriteManagers = new Array();
  23336. /**
  23337. * The list of layers (background and foreground) of the scene
  23338. */
  23339. this.layers = new Array();
  23340. /**
  23341. * The list of effect layers (highlights/glow) added to the scene
  23342. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23343. * @see http://doc.babylonjs.com/how_to/glow_layer
  23344. */
  23345. this.effectLayers = new Array();
  23346. // Skeletons
  23347. this._skeletonsEnabled = true;
  23348. /**
  23349. * The list of skeletons added to the scene
  23350. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23351. */
  23352. this.skeletons = new Array();
  23353. // Morph targets
  23354. /**
  23355. * The list of morph target managers added to the scene
  23356. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23357. */
  23358. this.morphTargetManagers = new Array();
  23359. // Lens flares
  23360. /**
  23361. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23362. */
  23363. this.lensFlaresEnabled = true;
  23364. /**
  23365. * The list of lens flare system added to the scene
  23366. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23367. */
  23368. this.lensFlareSystems = new Array();
  23369. // Collisions
  23370. /**
  23371. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23372. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23373. */
  23374. this.collisionsEnabled = true;
  23375. /**
  23376. * Defines the gravity applied to this scene (used only for collisions)
  23377. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23378. */
  23379. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23380. // Postprocesses
  23381. /**
  23382. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23383. */
  23384. this.postProcessesEnabled = true;
  23385. /**
  23386. * The list of postprocesses added to the scene
  23387. */
  23388. this.postProcesses = new Array();
  23389. // Customs render targets
  23390. /**
  23391. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23392. */
  23393. this.renderTargetsEnabled = true;
  23394. /**
  23395. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23396. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23397. */
  23398. this.dumpNextRenderTargets = false;
  23399. /**
  23400. * The list of user defined render targets added to the scene
  23401. */
  23402. this.customRenderTargets = new Array();
  23403. /**
  23404. * Gets the list of meshes imported to the scene through SceneLoader
  23405. */
  23406. this.importedMeshesFiles = new Array();
  23407. // Probes
  23408. /**
  23409. * Gets or sets a boolean indicating if probes are enabled on this scene
  23410. */
  23411. this.probesEnabled = true;
  23412. /**
  23413. * The list of reflection probes added to the scene
  23414. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23415. */
  23416. this.reflectionProbes = new Array();
  23417. /** @ignore */
  23418. this._actionManagers = new Array();
  23419. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23420. // Procedural textures
  23421. /**
  23422. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23423. */
  23424. this.proceduralTexturesEnabled = true;
  23425. /**
  23426. * The list of procedural textures added to the scene
  23427. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23428. */
  23429. this.proceduralTextures = new Array();
  23430. /**
  23431. * The list of sound tracks added to the scene
  23432. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23433. */
  23434. this.soundTracks = new Array();
  23435. this._audioEnabled = true;
  23436. this._headphone = false;
  23437. // Performance counters
  23438. this._totalVertices = new BABYLON.PerfCounter();
  23439. /** @ignore */
  23440. this._activeIndices = new BABYLON.PerfCounter();
  23441. /** @ignore */
  23442. this._activeParticles = new BABYLON.PerfCounter();
  23443. /** @ignore */
  23444. this._activeBones = new BABYLON.PerfCounter();
  23445. this._animationTime = 0;
  23446. /**
  23447. * Gets or sets a general scale for animation speed
  23448. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23449. */
  23450. this.animationTimeScale = 1;
  23451. this._renderId = 0;
  23452. this._executeWhenReadyTimeoutId = -1;
  23453. this._intermediateRendering = false;
  23454. this._viewUpdateFlag = -1;
  23455. this._projectionUpdateFlag = -1;
  23456. this._alternateViewUpdateFlag = -1;
  23457. this._alternateProjectionUpdateFlag = -1;
  23458. /** @ignore */
  23459. this._toBeDisposed = new BABYLON.SmartArray(256);
  23460. this._activeRequests = new Array();
  23461. this._pendingData = new Array();
  23462. this._isDisposed = false;
  23463. /**
  23464. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23465. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23466. */
  23467. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23468. this._activeMeshes = new BABYLON.SmartArray(256);
  23469. this._processedMaterials = new BABYLON.SmartArray(256);
  23470. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23471. /** @ignore */
  23472. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23473. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23474. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23475. /** @ignore */
  23476. this._activeAnimatables = new Array();
  23477. this._transformMatrix = BABYLON.Matrix.Zero();
  23478. this._useAlternateCameraConfiguration = false;
  23479. this._alternateRendering = false;
  23480. /**
  23481. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23482. * This is useful if there are more lights that the maximum simulteanous authorized
  23483. */
  23484. this.requireLightSorting = false;
  23485. this._depthRenderer = {};
  23486. this._activeMeshesFrozen = false;
  23487. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23488. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23489. this._engine.scenes.push(this);
  23490. this._uid = null;
  23491. this._renderingManager = new BABYLON.RenderingManager(this);
  23492. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23493. if (BABYLON.OutlineRenderer) {
  23494. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23495. }
  23496. if (BABYLON.Tools.IsWindowObjectExist()) {
  23497. this.attachControl();
  23498. }
  23499. //simplification queue
  23500. if (BABYLON.SimplificationQueue) {
  23501. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23502. }
  23503. //collision coordinator initialization. For now legacy per default.
  23504. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23505. // Uniform Buffer
  23506. this._createUbo();
  23507. // Default Image processing definition.
  23508. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23509. }
  23510. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23511. /** The fog is deactivated */
  23512. get: function () {
  23513. return Scene._FOGMODE_NONE;
  23514. },
  23515. enumerable: true,
  23516. configurable: true
  23517. });
  23518. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23519. /** The fog density is following an exponential function */
  23520. get: function () {
  23521. return Scene._FOGMODE_EXP;
  23522. },
  23523. enumerable: true,
  23524. configurable: true
  23525. });
  23526. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23527. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23528. get: function () {
  23529. return Scene._FOGMODE_EXP2;
  23530. },
  23531. enumerable: true,
  23532. configurable: true
  23533. });
  23534. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23535. /** The fog density is following a linear function. */
  23536. get: function () {
  23537. return Scene._FOGMODE_LINEAR;
  23538. },
  23539. enumerable: true,
  23540. configurable: true
  23541. });
  23542. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23543. /**
  23544. * Texture used in all pbr material as the reflection texture.
  23545. * As in the majority of the scene they are the same (exception for multi room and so on),
  23546. * this is easier to reference from here than from all the materials.
  23547. */
  23548. get: function () {
  23549. return this._environmentTexture;
  23550. },
  23551. /**
  23552. * Texture used in all pbr material as the reflection texture.
  23553. * As in the majority of the scene they are the same (exception for multi room and so on),
  23554. * this is easier to set here than in all the materials.
  23555. */
  23556. set: function (value) {
  23557. if (this._environmentTexture === value) {
  23558. return;
  23559. }
  23560. this._environmentTexture = value;
  23561. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23562. },
  23563. enumerable: true,
  23564. configurable: true
  23565. });
  23566. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23567. /**
  23568. * Default image processing configuration used either in the rendering
  23569. * Forward main pass or through the imageProcessingPostProcess if present.
  23570. * As in the majority of the scene they are the same (exception for multi camera),
  23571. * this is easier to reference from here than from all the materials and post process.
  23572. *
  23573. * No setter as we it is a shared configuration, you can set the values instead.
  23574. */
  23575. get: function () {
  23576. return this._imageProcessingConfiguration;
  23577. },
  23578. enumerable: true,
  23579. configurable: true
  23580. });
  23581. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23582. get: function () {
  23583. return this._forceWireframe;
  23584. },
  23585. /**
  23586. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23587. */
  23588. set: function (value) {
  23589. if (this._forceWireframe === value) {
  23590. return;
  23591. }
  23592. this._forceWireframe = value;
  23593. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23594. },
  23595. enumerable: true,
  23596. configurable: true
  23597. });
  23598. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23599. get: function () {
  23600. return this._forcePointsCloud;
  23601. },
  23602. /**
  23603. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23604. */
  23605. set: function (value) {
  23606. if (this._forcePointsCloud === value) {
  23607. return;
  23608. }
  23609. this._forcePointsCloud = value;
  23610. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23611. },
  23612. enumerable: true,
  23613. configurable: true
  23614. });
  23615. Object.defineProperty(Scene.prototype, "onDispose", {
  23616. /** Sets a function to be executed when this scene is disposed. */
  23617. set: function (callback) {
  23618. if (this._onDisposeObserver) {
  23619. this.onDisposeObservable.remove(this._onDisposeObserver);
  23620. }
  23621. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23622. },
  23623. enumerable: true,
  23624. configurable: true
  23625. });
  23626. Object.defineProperty(Scene.prototype, "beforeRender", {
  23627. /** Sets a function to be executed before rendering this scene */
  23628. set: function (callback) {
  23629. if (this._onBeforeRenderObserver) {
  23630. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23631. }
  23632. if (callback) {
  23633. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23634. }
  23635. },
  23636. enumerable: true,
  23637. configurable: true
  23638. });
  23639. Object.defineProperty(Scene.prototype, "afterRender", {
  23640. /** Sets a function to be executed after rendering this scene */
  23641. set: function (callback) {
  23642. if (this._onAfterRenderObserver) {
  23643. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23644. }
  23645. if (callback) {
  23646. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23647. }
  23648. },
  23649. enumerable: true,
  23650. configurable: true
  23651. });
  23652. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  23653. /** Sets a function to be executed before rendering a camera*/
  23654. set: function (callback) {
  23655. if (this._onBeforeCameraRenderObserver) {
  23656. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  23657. }
  23658. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  23659. },
  23660. enumerable: true,
  23661. configurable: true
  23662. });
  23663. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  23664. /** Sets a function to be executed after rendering a camera*/
  23665. set: function (callback) {
  23666. if (this._onAfterCameraRenderObserver) {
  23667. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  23668. }
  23669. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  23670. },
  23671. enumerable: true,
  23672. configurable: true
  23673. });
  23674. Object.defineProperty(Scene.prototype, "gamepadManager", {
  23675. /**
  23676. * Gets the gamepad manager associated with the scene
  23677. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  23678. */
  23679. get: function () {
  23680. if (!this._gamepadManager) {
  23681. this._gamepadManager = new BABYLON.GamepadManager(this);
  23682. }
  23683. return this._gamepadManager;
  23684. },
  23685. enumerable: true,
  23686. configurable: true
  23687. });
  23688. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  23689. /**
  23690. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  23691. */
  23692. get: function () {
  23693. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  23694. },
  23695. enumerable: true,
  23696. configurable: true
  23697. });
  23698. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  23699. get: function () {
  23700. return this._useRightHandedSystem;
  23701. },
  23702. /**
  23703. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  23704. */
  23705. set: function (value) {
  23706. if (this._useRightHandedSystem === value) {
  23707. return;
  23708. }
  23709. this._useRightHandedSystem = value;
  23710. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23711. },
  23712. enumerable: true,
  23713. configurable: true
  23714. });
  23715. /**
  23716. * Sets the step Id used by deterministic lock step
  23717. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23718. * @param newStepId defines the step Id
  23719. */
  23720. Scene.prototype.setStepId = function (newStepId) {
  23721. this._currentStepId = newStepId;
  23722. };
  23723. ;
  23724. /**
  23725. * Gets the step Id used by deterministic lock step
  23726. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23727. * @returns the step Id
  23728. */
  23729. Scene.prototype.getStepId = function () {
  23730. return this._currentStepId;
  23731. };
  23732. ;
  23733. /**
  23734. * Gets the internal step used by deterministic lock step
  23735. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23736. * @returns the internal step
  23737. */
  23738. Scene.prototype.getInternalStep = function () {
  23739. return this._currentInternalStep;
  23740. };
  23741. ;
  23742. Object.defineProperty(Scene.prototype, "fogEnabled", {
  23743. get: function () {
  23744. return this._fogEnabled;
  23745. },
  23746. /**
  23747. * Gets or sets a boolean indicating if fog is enabled on this scene
  23748. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23749. */
  23750. set: function (value) {
  23751. if (this._fogEnabled === value) {
  23752. return;
  23753. }
  23754. this._fogEnabled = value;
  23755. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23756. },
  23757. enumerable: true,
  23758. configurable: true
  23759. });
  23760. Object.defineProperty(Scene.prototype, "fogMode", {
  23761. get: function () {
  23762. return this._fogMode;
  23763. },
  23764. /**
  23765. * Gets or sets the fog mode to use
  23766. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23767. */
  23768. set: function (value) {
  23769. if (this._fogMode === value) {
  23770. return;
  23771. }
  23772. this._fogMode = value;
  23773. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23774. },
  23775. enumerable: true,
  23776. configurable: true
  23777. });
  23778. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  23779. get: function () {
  23780. return this._shadowsEnabled;
  23781. },
  23782. /**
  23783. * Gets or sets a boolean indicating if shadows are enabled on this scene
  23784. */
  23785. set: function (value) {
  23786. if (this._shadowsEnabled === value) {
  23787. return;
  23788. }
  23789. this._shadowsEnabled = value;
  23790. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23791. },
  23792. enumerable: true,
  23793. configurable: true
  23794. });
  23795. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  23796. get: function () {
  23797. return this._lightsEnabled;
  23798. },
  23799. /**
  23800. * Gets or sets a boolean indicating if lights are enabled on this scene
  23801. */
  23802. set: function (value) {
  23803. if (this._lightsEnabled === value) {
  23804. return;
  23805. }
  23806. this._lightsEnabled = value;
  23807. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23808. },
  23809. enumerable: true,
  23810. configurable: true
  23811. });
  23812. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  23813. /** The default material used on meshes when no material is affected */
  23814. get: function () {
  23815. if (!this._defaultMaterial) {
  23816. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  23817. }
  23818. return this._defaultMaterial;
  23819. },
  23820. /** The default material used on meshes when no material is affected */
  23821. set: function (value) {
  23822. this._defaultMaterial = value;
  23823. },
  23824. enumerable: true,
  23825. configurable: true
  23826. });
  23827. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  23828. get: function () {
  23829. return this._texturesEnabled;
  23830. },
  23831. /**
  23832. * Gets or sets a boolean indicating if textures are enabled on this scene
  23833. */
  23834. set: function (value) {
  23835. if (this._texturesEnabled === value) {
  23836. return;
  23837. }
  23838. this._texturesEnabled = value;
  23839. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23840. },
  23841. enumerable: true,
  23842. configurable: true
  23843. });
  23844. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  23845. get: function () {
  23846. return this._skeletonsEnabled;
  23847. },
  23848. /**
  23849. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  23850. */
  23851. set: function (value) {
  23852. if (this._skeletonsEnabled === value) {
  23853. return;
  23854. }
  23855. this._skeletonsEnabled = value;
  23856. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  23857. },
  23858. enumerable: true,
  23859. configurable: true
  23860. });
  23861. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  23862. /**
  23863. * Gets the postprocess render pipeline manager
  23864. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  23865. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  23866. */
  23867. get: function () {
  23868. if (!this._postProcessRenderPipelineManager) {
  23869. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  23870. }
  23871. return this._postProcessRenderPipelineManager;
  23872. },
  23873. enumerable: true,
  23874. configurable: true
  23875. });
  23876. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  23877. /**
  23878. * Gets the main soundtrack associated with the scene
  23879. */
  23880. get: function () {
  23881. if (!this._mainSoundTrack) {
  23882. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  23883. }
  23884. return this._mainSoundTrack;
  23885. },
  23886. enumerable: true,
  23887. configurable: true
  23888. });
  23889. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  23890. /** @ignore */
  23891. get: function () {
  23892. return this._alternateRendering;
  23893. },
  23894. enumerable: true,
  23895. configurable: true
  23896. });
  23897. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  23898. /**
  23899. * Gets the list of frustum planes (built from the active camera)
  23900. */
  23901. get: function () {
  23902. return this._frustumPlanes;
  23903. },
  23904. enumerable: true,
  23905. configurable: true
  23906. });
  23907. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  23908. /**
  23909. * Gets the current geometry buffer associated to the scene.
  23910. */
  23911. get: function () {
  23912. return this._geometryBufferRenderer;
  23913. },
  23914. /**
  23915. * Sets the current geometry buffer for the scene.
  23916. */
  23917. set: function (geometryBufferRenderer) {
  23918. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  23919. this._geometryBufferRenderer = geometryBufferRenderer;
  23920. }
  23921. },
  23922. enumerable: true,
  23923. configurable: true
  23924. });
  23925. Object.defineProperty(Scene.prototype, "debugLayer", {
  23926. /**
  23927. * Gets the debug layer associated with the scene
  23928. * @see http://doc.babylonjs.com/features/playground_debuglayer
  23929. */
  23930. get: function () {
  23931. if (!this._debugLayer) {
  23932. this._debugLayer = new BABYLON.DebugLayer(this);
  23933. }
  23934. return this._debugLayer;
  23935. },
  23936. enumerable: true,
  23937. configurable: true
  23938. });
  23939. Object.defineProperty(Scene.prototype, "workerCollisions", {
  23940. /**
  23941. * Gets a boolean indicating if collisions are processed on a web worker
  23942. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  23943. */
  23944. get: function () {
  23945. return this._workerCollisions;
  23946. },
  23947. set: function (enabled) {
  23948. if (!BABYLON.CollisionCoordinatorLegacy) {
  23949. return;
  23950. }
  23951. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  23952. this._workerCollisions = enabled;
  23953. if (this.collisionCoordinator) {
  23954. this.collisionCoordinator.destroy();
  23955. }
  23956. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  23957. this.collisionCoordinator.init(this);
  23958. },
  23959. enumerable: true,
  23960. configurable: true
  23961. });
  23962. Object.defineProperty(Scene.prototype, "selectionOctree", {
  23963. /**
  23964. * Gets the octree used to boost mesh selection (picking)
  23965. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  23966. */
  23967. get: function () {
  23968. return this._selectionOctree;
  23969. },
  23970. enumerable: true,
  23971. configurable: true
  23972. });
  23973. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  23974. /**
  23975. * Gets the mesh that is currently under the pointer
  23976. */
  23977. get: function () {
  23978. return this._pointerOverMesh;
  23979. },
  23980. enumerable: true,
  23981. configurable: true
  23982. });
  23983. Object.defineProperty(Scene.prototype, "pointerX", {
  23984. /**
  23985. * Gets the current on-screen X position of the pointer
  23986. */
  23987. get: function () {
  23988. return this._pointerX;
  23989. },
  23990. enumerable: true,
  23991. configurable: true
  23992. });
  23993. Object.defineProperty(Scene.prototype, "pointerY", {
  23994. /**
  23995. * Gets the current on-screen Y position of the pointer
  23996. */
  23997. get: function () {
  23998. return this._pointerY;
  23999. },
  24000. enumerable: true,
  24001. configurable: true
  24002. });
  24003. /**
  24004. * Gets the cached material (ie. the latest rendered one)
  24005. * @returns the cached material
  24006. */
  24007. Scene.prototype.getCachedMaterial = function () {
  24008. return this._cachedMaterial;
  24009. };
  24010. /**
  24011. * Gets the cached effect (ie. the latest rendered one)
  24012. * @returns the cached effect
  24013. */
  24014. Scene.prototype.getCachedEffect = function () {
  24015. return this._cachedEffect;
  24016. };
  24017. /**
  24018. * Gets the cached visibility state (ie. the latest rendered one)
  24019. * @returns the cached visibility state
  24020. */
  24021. Scene.prototype.getCachedVisibility = function () {
  24022. return this._cachedVisibility;
  24023. };
  24024. /**
  24025. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24026. * @param material defines the current material
  24027. * @param effect defines the current effect
  24028. * @param visibility defines the current visibility state
  24029. * @returns true if one parameter is not cached
  24030. */
  24031. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24032. if (visibility === void 0) { visibility = 1; }
  24033. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24034. };
  24035. /**
  24036. * Gets the bounding box renderer associated with the scene
  24037. * @returns a BoundingBoxRenderer
  24038. */
  24039. Scene.prototype.getBoundingBoxRenderer = function () {
  24040. if (!this._boundingBoxRenderer) {
  24041. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24042. }
  24043. return this._boundingBoxRenderer;
  24044. };
  24045. /**
  24046. * Gets the outline renderer associated with the scene
  24047. * @returns a OutlineRenderer
  24048. */
  24049. Scene.prototype.getOutlineRenderer = function () {
  24050. return this._outlineRenderer;
  24051. };
  24052. /**
  24053. * Gets the engine associated with the scene
  24054. * @returns an Engine
  24055. */
  24056. Scene.prototype.getEngine = function () {
  24057. return this._engine;
  24058. };
  24059. /**
  24060. * Gets the total number of vertices rendered per frame
  24061. * @returns the total number of vertices rendered per frame
  24062. */
  24063. Scene.prototype.getTotalVertices = function () {
  24064. return this._totalVertices.current;
  24065. };
  24066. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24067. /**
  24068. * Gets the performance counter for total vertices
  24069. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24070. */
  24071. get: function () {
  24072. return this._totalVertices;
  24073. },
  24074. enumerable: true,
  24075. configurable: true
  24076. });
  24077. /**
  24078. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24079. * @returns the total number of active indices rendered per frame
  24080. */
  24081. Scene.prototype.getActiveIndices = function () {
  24082. return this._activeIndices.current;
  24083. };
  24084. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24085. /**
  24086. * Gets the performance counter for active indices
  24087. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24088. */
  24089. get: function () {
  24090. return this._activeIndices;
  24091. },
  24092. enumerable: true,
  24093. configurable: true
  24094. });
  24095. /**
  24096. * Gets the total number of active particles rendered per frame
  24097. * @returns the total number of active particles rendered per frame
  24098. */
  24099. Scene.prototype.getActiveParticles = function () {
  24100. return this._activeParticles.current;
  24101. };
  24102. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24103. /**
  24104. * Gets the performance counter for active particles
  24105. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24106. */
  24107. get: function () {
  24108. return this._activeParticles;
  24109. },
  24110. enumerable: true,
  24111. configurable: true
  24112. });
  24113. /**
  24114. * Gets the total number of active bones rendered per frame
  24115. * @returns the total number of active bones rendered per frame
  24116. */
  24117. Scene.prototype.getActiveBones = function () {
  24118. return this._activeBones.current;
  24119. };
  24120. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24121. /**
  24122. * Gets the performance counter for active bones
  24123. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24124. */
  24125. get: function () {
  24126. return this._activeBones;
  24127. },
  24128. enumerable: true,
  24129. configurable: true
  24130. });
  24131. /** @ignore */
  24132. Scene.prototype.getInterFramePerfCounter = function () {
  24133. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24134. return 0;
  24135. };
  24136. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24137. /** @ignore */
  24138. get: function () {
  24139. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24140. return null;
  24141. },
  24142. enumerable: true,
  24143. configurable: true
  24144. });
  24145. /** @ignore */
  24146. Scene.prototype.getLastFrameDuration = function () {
  24147. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24148. return 0;
  24149. };
  24150. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24151. /** @ignore */
  24152. get: function () {
  24153. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24154. return null;
  24155. },
  24156. enumerable: true,
  24157. configurable: true
  24158. });
  24159. /** @ignore */
  24160. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24161. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24162. return 0;
  24163. };
  24164. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24165. /** @ignore */
  24166. get: function () {
  24167. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24168. return null;
  24169. },
  24170. enumerable: true,
  24171. configurable: true
  24172. });
  24173. /**
  24174. * Gets the array of active meshes
  24175. * @returns an array of AbstractMesh
  24176. */
  24177. Scene.prototype.getActiveMeshes = function () {
  24178. return this._activeMeshes;
  24179. };
  24180. /** @ignore */
  24181. Scene.prototype.getRenderTargetsDuration = function () {
  24182. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24183. return 0;
  24184. };
  24185. /** @ignore */
  24186. Scene.prototype.getRenderDuration = function () {
  24187. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24188. return 0;
  24189. };
  24190. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24191. /** @ignore */
  24192. get: function () {
  24193. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24194. return null;
  24195. },
  24196. enumerable: true,
  24197. configurable: true
  24198. });
  24199. /** @ignore */
  24200. Scene.prototype.getParticlesDuration = function () {
  24201. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24202. return 0;
  24203. };
  24204. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24205. /** @ignore */
  24206. get: function () {
  24207. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24208. return null;
  24209. },
  24210. enumerable: true,
  24211. configurable: true
  24212. });
  24213. /** @ignore */
  24214. Scene.prototype.getSpritesDuration = function () {
  24215. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24216. return 0;
  24217. };
  24218. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24219. /** @ignore */
  24220. get: function () {
  24221. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24222. return null;
  24223. },
  24224. enumerable: true,
  24225. configurable: true
  24226. });
  24227. /**
  24228. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24229. * @returns a number
  24230. */
  24231. Scene.prototype.getAnimationRatio = function () {
  24232. return this._animationRatio;
  24233. };
  24234. /**
  24235. * Gets an unique Id for the current frame
  24236. * @returns a number
  24237. */
  24238. Scene.prototype.getRenderId = function () {
  24239. return this._renderId;
  24240. };
  24241. /** Call this function if you want to manually increment the render Id*/
  24242. Scene.prototype.incrementRenderId = function () {
  24243. this._renderId++;
  24244. };
  24245. Scene.prototype._updatePointerPosition = function (evt) {
  24246. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24247. if (!canvasRect) {
  24248. return;
  24249. }
  24250. this._pointerX = evt.clientX - canvasRect.left;
  24251. this._pointerY = evt.clientY - canvasRect.top;
  24252. this._unTranslatedPointerX = this._pointerX;
  24253. this._unTranslatedPointerY = this._pointerY;
  24254. };
  24255. Scene.prototype._createUbo = function () {
  24256. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24257. this._sceneUbo.addUniform("viewProjection", 16);
  24258. this._sceneUbo.addUniform("view", 16);
  24259. };
  24260. Scene.prototype._createAlternateUbo = function () {
  24261. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24262. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24263. this._alternateSceneUbo.addUniform("view", 16);
  24264. };
  24265. // Pointers handling
  24266. /**
  24267. * Use this method to simulate a pointer move on a mesh
  24268. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24269. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24270. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24271. * @returns the current scene
  24272. */
  24273. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24274. var evt = new PointerEvent("pointermove", pointerEventInit);
  24275. return this._processPointerMove(pickResult, evt);
  24276. };
  24277. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24278. var canvas = this._engine.getRenderingCanvas();
  24279. if (!canvas) {
  24280. return this;
  24281. }
  24282. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24283. this.setPointerOverSprite(null);
  24284. this.setPointerOverMesh(pickResult.pickedMesh);
  24285. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24286. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24287. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24288. }
  24289. else {
  24290. canvas.style.cursor = this.hoverCursor;
  24291. }
  24292. }
  24293. else {
  24294. canvas.style.cursor = this.defaultCursor;
  24295. }
  24296. }
  24297. else {
  24298. this.setPointerOverMesh(null);
  24299. // Sprites
  24300. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24301. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24302. this.setPointerOverSprite(pickResult.pickedSprite);
  24303. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24304. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24305. }
  24306. else {
  24307. canvas.style.cursor = this.hoverCursor;
  24308. }
  24309. }
  24310. else {
  24311. this.setPointerOverSprite(null);
  24312. // Restore pointer
  24313. canvas.style.cursor = this.defaultCursor;
  24314. }
  24315. }
  24316. if (pickResult) {
  24317. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24318. if (this.onPointerMove) {
  24319. this.onPointerMove(evt, pickResult, type);
  24320. }
  24321. if (this.onPointerObservable.hasObservers()) {
  24322. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24323. this.onPointerObservable.notifyObservers(pi, type);
  24324. }
  24325. }
  24326. return this;
  24327. };
  24328. /**
  24329. * Use this method to simulate a pointer down on a mesh
  24330. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24331. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24332. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24333. * @returns the current scene
  24334. */
  24335. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24336. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24337. return this._processPointerDown(pickResult, evt);
  24338. };
  24339. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24340. var _this = this;
  24341. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24342. this._pickedDownMesh = pickResult.pickedMesh;
  24343. var actionManager = pickResult.pickedMesh.actionManager;
  24344. if (actionManager) {
  24345. if (actionManager.hasPickTriggers) {
  24346. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24347. switch (evt.button) {
  24348. case 0:
  24349. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24350. break;
  24351. case 1:
  24352. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24353. break;
  24354. case 2:
  24355. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24356. break;
  24357. }
  24358. }
  24359. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24360. window.setTimeout(function () {
  24361. 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);
  24362. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24363. if (_this._totalPointersPressed !== 0 &&
  24364. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24365. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24366. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24367. _this._startingPointerTime = 0;
  24368. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24369. }
  24370. }
  24371. }, Scene.LongPressDelay);
  24372. }
  24373. }
  24374. }
  24375. if (pickResult) {
  24376. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24377. if (this.onPointerDown) {
  24378. this.onPointerDown(evt, pickResult, type);
  24379. }
  24380. if (this.onPointerObservable.hasObservers()) {
  24381. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24382. this.onPointerObservable.notifyObservers(pi, type);
  24383. }
  24384. }
  24385. return this;
  24386. };
  24387. /**
  24388. * Use this method to simulate a pointer up on a mesh
  24389. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24390. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24391. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24392. * @returns the current scene
  24393. */
  24394. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24395. var evt = new PointerEvent("pointerup", pointerEventInit);
  24396. var clickInfo = new ClickInfo();
  24397. clickInfo.singleClick = true;
  24398. clickInfo.ignore = true;
  24399. return this._processPointerUp(pickResult, evt, clickInfo);
  24400. };
  24401. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24402. if (pickResult && pickResult && pickResult.pickedMesh) {
  24403. this._pickedUpMesh = pickResult.pickedMesh;
  24404. if (this._pickedDownMesh === this._pickedUpMesh) {
  24405. if (this.onPointerPick) {
  24406. this.onPointerPick(evt, pickResult);
  24407. }
  24408. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24409. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24410. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24411. this.onPointerObservable.notifyObservers(pi, type_1);
  24412. }
  24413. }
  24414. if (pickResult.pickedMesh.actionManager) {
  24415. if (clickInfo.ignore) {
  24416. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24417. }
  24418. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24419. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24420. }
  24421. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24422. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24423. }
  24424. }
  24425. }
  24426. if (this._pickedDownMesh &&
  24427. this._pickedDownMesh.actionManager &&
  24428. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24429. this._pickedDownMesh !== this._pickedUpMesh) {
  24430. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24431. }
  24432. var type = BABYLON.PointerEventTypes.POINTERUP;
  24433. if (this.onPointerObservable.hasObservers()) {
  24434. if (!clickInfo.ignore) {
  24435. if (!clickInfo.hasSwiped) {
  24436. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24437. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24438. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24439. this.onPointerObservable.notifyObservers(pi, type_2);
  24440. }
  24441. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24442. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24443. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24444. this.onPointerObservable.notifyObservers(pi, type_3);
  24445. }
  24446. }
  24447. }
  24448. else {
  24449. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24450. this.onPointerObservable.notifyObservers(pi, type);
  24451. }
  24452. }
  24453. if (this.onPointerUp) {
  24454. this.onPointerUp(evt, pickResult, type);
  24455. }
  24456. return this;
  24457. };
  24458. /**
  24459. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24460. * @param attachUp defines if you want to attach events to pointerup
  24461. * @param attachDown defines if you want to attach events to pointerdown
  24462. * @param attachMove defines if you want to attach events to pointermove
  24463. */
  24464. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24465. var _this = this;
  24466. if (attachUp === void 0) { attachUp = true; }
  24467. if (attachDown === void 0) { attachDown = true; }
  24468. if (attachMove === void 0) { attachMove = true; }
  24469. this._initActionManager = function (act, clickInfo) {
  24470. if (!_this._meshPickProceed) {
  24471. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24472. _this._currentPickResult = pickResult;
  24473. if (pickResult) {
  24474. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24475. }
  24476. _this._meshPickProceed = true;
  24477. }
  24478. return act;
  24479. };
  24480. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24481. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24482. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24483. btn !== _this._previousButtonPressed) {
  24484. _this._doubleClickOccured = false;
  24485. clickInfo.singleClick = true;
  24486. clickInfo.ignore = false;
  24487. cb(clickInfo, _this._currentPickResult);
  24488. }
  24489. };
  24490. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24491. var clickInfo = new ClickInfo();
  24492. _this._currentPickResult = null;
  24493. var act = null;
  24494. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24495. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24496. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24497. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24498. act = _this._initActionManager(act, clickInfo);
  24499. if (act)
  24500. checkPicking = act.hasPickTriggers;
  24501. }
  24502. if (checkPicking) {
  24503. var btn = evt.button;
  24504. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24505. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24506. if (!clickInfo.hasSwiped) {
  24507. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24508. if (!checkSingleClickImmediately) {
  24509. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24510. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24511. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24512. act = _this._initActionManager(act, clickInfo);
  24513. if (act)
  24514. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24515. }
  24516. }
  24517. if (checkSingleClickImmediately) {
  24518. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24519. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24520. btn !== _this._previousButtonPressed) {
  24521. clickInfo.singleClick = true;
  24522. cb(clickInfo, _this._currentPickResult);
  24523. }
  24524. }
  24525. else {
  24526. // wait that no double click has been raised during the double click delay
  24527. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24528. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24529. }
  24530. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24531. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24532. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24533. act = _this._initActionManager(act, clickInfo);
  24534. if (act)
  24535. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24536. }
  24537. if (checkDoubleClick) {
  24538. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24539. if (btn === _this._previousButtonPressed &&
  24540. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24541. !_this._doubleClickOccured) {
  24542. // pointer has not moved for 2 clicks, it's a double click
  24543. if (!clickInfo.hasSwiped &&
  24544. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24545. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24546. _this._previousStartingPointerTime = 0;
  24547. _this._doubleClickOccured = true;
  24548. clickInfo.doubleClick = true;
  24549. clickInfo.ignore = false;
  24550. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24551. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24552. }
  24553. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24554. cb(clickInfo, _this._currentPickResult);
  24555. }
  24556. else {
  24557. _this._doubleClickOccured = false;
  24558. _this._previousStartingPointerTime = _this._startingPointerTime;
  24559. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24560. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24561. _this._previousButtonPressed = btn;
  24562. if (Scene.ExclusiveDoubleClickMode) {
  24563. if (_this._previousDelayedSimpleClickTimeout) {
  24564. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24565. }
  24566. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24567. cb(clickInfo, _this._previousPickResult);
  24568. }
  24569. else {
  24570. cb(clickInfo, _this._currentPickResult);
  24571. }
  24572. }
  24573. }
  24574. else {
  24575. _this._doubleClickOccured = false;
  24576. _this._previousStartingPointerTime = _this._startingPointerTime;
  24577. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24578. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24579. _this._previousButtonPressed = btn;
  24580. }
  24581. }
  24582. }
  24583. }
  24584. clickInfo.ignore = true;
  24585. cb(clickInfo, _this._currentPickResult);
  24586. };
  24587. this._spritePredicate = function (sprite) {
  24588. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24589. };
  24590. this._onPointerMove = function (evt) {
  24591. _this._updatePointerPosition(evt);
  24592. // PreObservable support
  24593. if (_this.onPrePointerObservable.hasObservers()) {
  24594. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24595. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24596. _this.onPrePointerObservable.notifyObservers(pi, type);
  24597. if (pi.skipOnPointerObservable) {
  24598. return;
  24599. }
  24600. }
  24601. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24602. return;
  24603. }
  24604. if (!_this.pointerMovePredicate) {
  24605. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24606. }
  24607. // Meshes
  24608. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24609. _this._processPointerMove(pickResult, evt);
  24610. };
  24611. this._onPointerDown = function (evt) {
  24612. _this._totalPointersPressed++;
  24613. _this._pickedDownMesh = null;
  24614. _this._meshPickProceed = false;
  24615. _this._updatePointerPosition(evt);
  24616. if (_this.preventDefaultOnPointerDown && canvas) {
  24617. evt.preventDefault();
  24618. canvas.focus();
  24619. }
  24620. // PreObservable support
  24621. if (_this.onPrePointerObservable.hasObservers()) {
  24622. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24623. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24624. _this.onPrePointerObservable.notifyObservers(pi, type);
  24625. if (pi.skipOnPointerObservable) {
  24626. return;
  24627. }
  24628. }
  24629. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24630. return;
  24631. }
  24632. _this._startingPointerPosition.x = _this._pointerX;
  24633. _this._startingPointerPosition.y = _this._pointerY;
  24634. _this._startingPointerTime = new Date().getTime();
  24635. if (!_this.pointerDownPredicate) {
  24636. _this.pointerDownPredicate = function (mesh) {
  24637. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24638. };
  24639. }
  24640. // Meshes
  24641. _this._pickedDownMesh = null;
  24642. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24643. _this._processPointerDown(pickResult, evt);
  24644. // Sprites
  24645. _this._pickedDownSprite = null;
  24646. if (_this.spriteManagers.length > 0) {
  24647. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24648. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24649. if (pickResult.pickedSprite.actionManager) {
  24650. _this._pickedDownSprite = pickResult.pickedSprite;
  24651. switch (evt.button) {
  24652. case 0:
  24653. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24654. break;
  24655. case 1:
  24656. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24657. break;
  24658. case 2:
  24659. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24660. break;
  24661. }
  24662. if (pickResult.pickedSprite.actionManager) {
  24663. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24664. }
  24665. }
  24666. }
  24667. }
  24668. };
  24669. this._onPointerUp = function (evt) {
  24670. if (_this._totalPointersPressed === 0) {
  24671. return; // So we need to test it the pointer down was pressed before.
  24672. }
  24673. _this._totalPointersPressed--;
  24674. _this._pickedUpMesh = null;
  24675. _this._meshPickProceed = false;
  24676. _this._updatePointerPosition(evt);
  24677. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  24678. // PreObservable support
  24679. if (_this.onPrePointerObservable.hasObservers()) {
  24680. if (!clickInfo.ignore) {
  24681. if (!clickInfo.hasSwiped) {
  24682. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24683. var type = BABYLON.PointerEventTypes.POINTERTAP;
  24684. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24685. _this.onPrePointerObservable.notifyObservers(pi, type);
  24686. if (pi.skipOnPointerObservable) {
  24687. return;
  24688. }
  24689. }
  24690. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24691. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24692. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24693. _this.onPrePointerObservable.notifyObservers(pi, type);
  24694. if (pi.skipOnPointerObservable) {
  24695. return;
  24696. }
  24697. }
  24698. }
  24699. }
  24700. else {
  24701. var type = BABYLON.PointerEventTypes.POINTERUP;
  24702. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24703. _this.onPrePointerObservable.notifyObservers(pi, type);
  24704. if (pi.skipOnPointerObservable) {
  24705. return;
  24706. }
  24707. }
  24708. }
  24709. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24710. return;
  24711. }
  24712. if (!_this.pointerUpPredicate) {
  24713. _this.pointerUpPredicate = function (mesh) {
  24714. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24715. };
  24716. }
  24717. // Meshes
  24718. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  24719. _this._initActionManager(null, clickInfo);
  24720. }
  24721. if (!pickResult) {
  24722. pickResult = _this._currentPickResult;
  24723. }
  24724. _this._processPointerUp(pickResult, evt, clickInfo);
  24725. // Sprites
  24726. if (_this.spriteManagers.length > 0) {
  24727. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24728. if (spritePickResult) {
  24729. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  24730. if (spritePickResult.pickedSprite.actionManager) {
  24731. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24732. if (spritePickResult.pickedSprite.actionManager) {
  24733. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  24734. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24735. }
  24736. }
  24737. }
  24738. }
  24739. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  24740. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  24741. }
  24742. }
  24743. }
  24744. _this._previousPickResult = _this._currentPickResult;
  24745. });
  24746. };
  24747. this._onKeyDown = function (evt) {
  24748. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  24749. if (_this.onPreKeyboardObservable.hasObservers()) {
  24750. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24751. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24752. if (pi.skipOnPointerObservable) {
  24753. return;
  24754. }
  24755. }
  24756. if (_this.onKeyboardObservable.hasObservers()) {
  24757. var pi = new BABYLON.KeyboardInfo(type, evt);
  24758. _this.onKeyboardObservable.notifyObservers(pi, type);
  24759. }
  24760. if (_this.actionManager) {
  24761. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24762. }
  24763. };
  24764. this._onKeyUp = function (evt) {
  24765. var type = BABYLON.KeyboardEventTypes.KEYUP;
  24766. if (_this.onPreKeyboardObservable.hasObservers()) {
  24767. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24768. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24769. if (pi.skipOnPointerObservable) {
  24770. return;
  24771. }
  24772. }
  24773. if (_this.onKeyboardObservable.hasObservers()) {
  24774. var pi = new BABYLON.KeyboardInfo(type, evt);
  24775. _this.onKeyboardObservable.notifyObservers(pi, type);
  24776. }
  24777. if (_this.actionManager) {
  24778. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24779. }
  24780. };
  24781. var engine = this.getEngine();
  24782. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  24783. if (!canvas) {
  24784. return;
  24785. }
  24786. canvas.addEventListener("keydown", _this._onKeyDown, false);
  24787. canvas.addEventListener("keyup", _this._onKeyUp, false);
  24788. });
  24789. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  24790. if (!canvas) {
  24791. return;
  24792. }
  24793. canvas.removeEventListener("keydown", _this._onKeyDown);
  24794. canvas.removeEventListener("keyup", _this._onKeyUp);
  24795. });
  24796. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24797. var canvas = this._engine.getRenderingCanvas();
  24798. if (!canvas) {
  24799. return;
  24800. }
  24801. if (attachMove) {
  24802. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  24803. // Wheel
  24804. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  24805. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  24806. }
  24807. if (attachDown) {
  24808. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  24809. }
  24810. if (attachUp) {
  24811. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  24812. }
  24813. canvas.tabIndex = 1;
  24814. };
  24815. /** Detaches all event handlers*/
  24816. Scene.prototype.detachControl = function () {
  24817. var engine = this.getEngine();
  24818. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24819. var canvas = engine.getRenderingCanvas();
  24820. if (!canvas) {
  24821. return;
  24822. }
  24823. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  24824. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  24825. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  24826. if (this._onCanvasBlurObserver) {
  24827. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  24828. }
  24829. if (this._onCanvasFocusObserver) {
  24830. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  24831. }
  24832. // Wheel
  24833. canvas.removeEventListener('mousewheel', this._onPointerMove);
  24834. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  24835. // Keyboard
  24836. canvas.removeEventListener("keydown", this._onKeyDown);
  24837. canvas.removeEventListener("keyup", this._onKeyUp);
  24838. // Observables
  24839. this.onKeyboardObservable.clear();
  24840. this.onPreKeyboardObservable.clear();
  24841. this.onPointerObservable.clear();
  24842. this.onPrePointerObservable.clear();
  24843. };
  24844. /**
  24845. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  24846. * Delay loaded resources are not taking in account
  24847. * @return true if all required resources are ready
  24848. */
  24849. Scene.prototype.isReady = function () {
  24850. if (this._isDisposed) {
  24851. return false;
  24852. }
  24853. if (this._pendingData.length > 0) {
  24854. return false;
  24855. }
  24856. var index;
  24857. var engine = this.getEngine();
  24858. // Geometries
  24859. for (index = 0; index < this._geometries.length; index++) {
  24860. var geometry = this._geometries[index];
  24861. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24862. return false;
  24863. }
  24864. }
  24865. // Meshes
  24866. for (index = 0; index < this.meshes.length; index++) {
  24867. var mesh = this.meshes[index];
  24868. if (!mesh.isEnabled()) {
  24869. continue;
  24870. }
  24871. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24872. continue;
  24873. }
  24874. if (!mesh.isReady(true)) {
  24875. return false;
  24876. }
  24877. // Effect layers
  24878. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  24879. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  24880. var layer = _a[_i];
  24881. if (!layer.hasMesh(mesh)) {
  24882. continue;
  24883. }
  24884. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24885. var subMesh = _c[_b];
  24886. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  24887. return false;
  24888. }
  24889. }
  24890. }
  24891. }
  24892. // Post-processes
  24893. if (this.activeCameras && this.activeCameras.length > 0) {
  24894. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  24895. var camera = _e[_d];
  24896. if (!camera.isReady(true)) {
  24897. return false;
  24898. }
  24899. }
  24900. }
  24901. else if (this.activeCamera) {
  24902. if (!this.activeCamera.isReady(true)) {
  24903. return false;
  24904. }
  24905. }
  24906. // Particles
  24907. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  24908. var particleSystem = _g[_f];
  24909. if (!particleSystem.isReady()) {
  24910. return false;
  24911. }
  24912. }
  24913. return true;
  24914. };
  24915. /** Resets all cached information relative to material (including effect and visibility) */
  24916. Scene.prototype.resetCachedMaterial = function () {
  24917. this._cachedMaterial = null;
  24918. this._cachedEffect = null;
  24919. this._cachedVisibility = null;
  24920. };
  24921. /**
  24922. * Registers a function to be called before every frame render
  24923. * @param func defines the function to register
  24924. */
  24925. Scene.prototype.registerBeforeRender = function (func) {
  24926. this.onBeforeRenderObservable.add(func);
  24927. };
  24928. /**
  24929. * Unregisters a function called before every frame render
  24930. * @param func defines the function to unregister
  24931. */
  24932. Scene.prototype.unregisterBeforeRender = function (func) {
  24933. this.onBeforeRenderObservable.removeCallback(func);
  24934. };
  24935. /**
  24936. * Registers a function to be called after every frame render
  24937. * @param func defines the function to register
  24938. */
  24939. Scene.prototype.registerAfterRender = function (func) {
  24940. this.onAfterRenderObservable.add(func);
  24941. };
  24942. /**
  24943. * Unregisters a function called after every frame render
  24944. * @param func defines the function to unregister
  24945. */
  24946. Scene.prototype.unregisterAfterRender = function (func) {
  24947. this.onAfterRenderObservable.removeCallback(func);
  24948. };
  24949. Scene.prototype._executeOnceBeforeRender = function (func) {
  24950. var _this = this;
  24951. var execFunc = function () {
  24952. func();
  24953. setTimeout(function () {
  24954. _this.unregisterBeforeRender(execFunc);
  24955. });
  24956. };
  24957. this.registerBeforeRender(execFunc);
  24958. };
  24959. /**
  24960. * The provided function will run before render once and will be disposed afterwards.
  24961. * A timeout delay can be provided so that the function will be executed in N ms.
  24962. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  24963. * @param func The function to be executed.
  24964. * @param timeout optional delay in ms
  24965. */
  24966. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  24967. var _this = this;
  24968. if (timeout !== undefined) {
  24969. setTimeout(function () {
  24970. _this._executeOnceBeforeRender(func);
  24971. }, timeout);
  24972. }
  24973. else {
  24974. this._executeOnceBeforeRender(func);
  24975. }
  24976. };
  24977. /** @ignore */
  24978. Scene.prototype._addPendingData = function (data) {
  24979. this._pendingData.push(data);
  24980. };
  24981. /** @ignore */
  24982. Scene.prototype._removePendingData = function (data) {
  24983. var wasLoading = this.isLoading;
  24984. var index = this._pendingData.indexOf(data);
  24985. if (index !== -1) {
  24986. this._pendingData.splice(index, 1);
  24987. }
  24988. if (wasLoading && !this.isLoading) {
  24989. this.onDataLoadedObservable.notifyObservers(this);
  24990. }
  24991. };
  24992. /**
  24993. * Returns the number of items waiting to be loaded
  24994. * @returns the number of items waiting to be loaded
  24995. */
  24996. Scene.prototype.getWaitingItemsCount = function () {
  24997. return this._pendingData.length;
  24998. };
  24999. Object.defineProperty(Scene.prototype, "isLoading", {
  25000. /**
  25001. * Returns a boolean indicating if the scene is still loading data
  25002. */
  25003. get: function () {
  25004. return this._pendingData.length > 0;
  25005. },
  25006. enumerable: true,
  25007. configurable: true
  25008. });
  25009. /**
  25010. * Registers a function to be executed when the scene is ready
  25011. * @param {Function} func - the function to be executed
  25012. */
  25013. Scene.prototype.executeWhenReady = function (func) {
  25014. var _this = this;
  25015. this.onReadyObservable.add(func);
  25016. if (this._executeWhenReadyTimeoutId !== -1) {
  25017. return;
  25018. }
  25019. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25020. _this._checkIsReady();
  25021. }, 150);
  25022. };
  25023. /**
  25024. * Returns a promise that resolves when the scene is ready
  25025. * @returns A promise that resolves when the scene is ready
  25026. */
  25027. Scene.prototype.whenReadyAsync = function () {
  25028. var _this = this;
  25029. return new Promise(function (resolve) {
  25030. _this.executeWhenReady(function () {
  25031. resolve();
  25032. });
  25033. });
  25034. };
  25035. /** @ignore */
  25036. Scene.prototype._checkIsReady = function () {
  25037. var _this = this;
  25038. if (this.isReady()) {
  25039. this.onReadyObservable.notifyObservers(this);
  25040. this.onReadyObservable.clear();
  25041. this._executeWhenReadyTimeoutId = -1;
  25042. return;
  25043. }
  25044. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25045. _this._checkIsReady();
  25046. }, 150);
  25047. };
  25048. // Animations
  25049. /**
  25050. * Will start the animation sequence of a given target
  25051. * @param target defines the target
  25052. * @param from defines from which frame should animation start
  25053. * @param to defines until which frame should animation run.
  25054. * @param weight defines the weight to apply to the animation (1.0 by default)
  25055. * @param loop defines if the animation loops
  25056. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25057. * @param onAnimationEnd defines the function to be executed when the animation ends
  25058. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25059. * @returns the animatable object created for this animation
  25060. */
  25061. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25062. if (weight === void 0) { weight = 1.0; }
  25063. if (speedRatio === void 0) { speedRatio = 1.0; }
  25064. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25065. returnedAnimatable.weight = weight;
  25066. return returnedAnimatable;
  25067. };
  25068. /**
  25069. * Will start the animation sequence of a given target
  25070. * @param target defines the target
  25071. * @param from defines from which frame should animation start
  25072. * @param to defines until which frame should animation run.
  25073. * @param loop defines if the animation loops
  25074. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25075. * @param onAnimationEnd defines the function to be executed when the animation ends
  25076. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25077. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25078. * @returns the animatable object created for this animation
  25079. */
  25080. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25081. if (speedRatio === void 0) { speedRatio = 1.0; }
  25082. if (stopCurrent === void 0) { stopCurrent = true; }
  25083. if (from > to && speedRatio > 0) {
  25084. speedRatio *= -1;
  25085. }
  25086. if (stopCurrent) {
  25087. this.stopAnimation(target);
  25088. }
  25089. if (!animatable) {
  25090. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25091. }
  25092. // Local animations
  25093. if (target.animations) {
  25094. animatable.appendAnimations(target, target.animations);
  25095. }
  25096. // Children animations
  25097. if (target.getAnimatables) {
  25098. var animatables = target.getAnimatables();
  25099. for (var index = 0; index < animatables.length; index++) {
  25100. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25101. }
  25102. }
  25103. animatable.reset();
  25104. return animatable;
  25105. };
  25106. /**
  25107. * Begin a new animation on a given node
  25108. * @param target defines the target where the animation will take place
  25109. * @param animations defines the list of animations to start
  25110. * @param from defines the initial value
  25111. * @param to defines the final value
  25112. * @param loop defines if you want animation to loop (off by default)
  25113. * @param speedRatio defines the speed ratio to apply to all animations
  25114. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25115. * @returns the list of created animatables
  25116. */
  25117. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25118. if (speedRatio === undefined) {
  25119. speedRatio = 1.0;
  25120. }
  25121. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25122. return animatable;
  25123. };
  25124. /**
  25125. * Begin a new animation on a given node and its hierarchy
  25126. * @param target defines the root node where the animation will take place
  25127. * @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.
  25128. * @param animations defines the list of animations to start
  25129. * @param from defines the initial value
  25130. * @param to defines the final value
  25131. * @param loop defines if you want animation to loop (off by default)
  25132. * @param speedRatio defines the speed ratio to apply to all animations
  25133. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25134. * @returns the list of animatables created for all nodes
  25135. */
  25136. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25137. var children = target.getDescendants(directDescendantsOnly);
  25138. var result = [];
  25139. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25140. var child = children_1[_i];
  25141. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25142. }
  25143. return result;
  25144. };
  25145. /**
  25146. * Gets the animatable associated with a specific target
  25147. * @param target defines the target of the animatable
  25148. * @returns the required animatable if found
  25149. */
  25150. Scene.prototype.getAnimatableByTarget = function (target) {
  25151. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25152. if (this._activeAnimatables[index].target === target) {
  25153. return this._activeAnimatables[index];
  25154. }
  25155. }
  25156. return null;
  25157. };
  25158. /**
  25159. * Gets all animatables associated with a given target
  25160. * @param target defines the target to look animatables for
  25161. * @returns an array of Animatables
  25162. */
  25163. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25164. var result = [];
  25165. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25166. if (this._activeAnimatables[index].target === target) {
  25167. result.push(this._activeAnimatables[index]);
  25168. }
  25169. }
  25170. return result;
  25171. };
  25172. Object.defineProperty(Scene.prototype, "animatables", {
  25173. /**
  25174. * Gets all animatable attached to the scene
  25175. */
  25176. get: function () {
  25177. return this._activeAnimatables;
  25178. },
  25179. enumerable: true,
  25180. configurable: true
  25181. });
  25182. /**
  25183. * Will stop the animation of the given target
  25184. * @param target - the target
  25185. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25186. */
  25187. Scene.prototype.stopAnimation = function (target, animationName) {
  25188. var animatables = this.getAllAnimatablesByTarget(target);
  25189. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25190. var animatable = animatables_1[_i];
  25191. animatable.stop(animationName);
  25192. }
  25193. };
  25194. /**
  25195. * Stops and removes all animations that have been applied to the scene
  25196. */
  25197. Scene.prototype.stopAllAnimations = function () {
  25198. if (this._activeAnimatables) {
  25199. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25200. this._activeAnimatables[i].stop();
  25201. }
  25202. this._activeAnimatables = [];
  25203. }
  25204. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25205. var group = _a[_i];
  25206. group.stop();
  25207. }
  25208. };
  25209. Scene.prototype._animate = function () {
  25210. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25211. return;
  25212. }
  25213. // Getting time
  25214. var now = BABYLON.Tools.Now;
  25215. if (!this._animationTimeLast) {
  25216. if (this._pendingData.length > 0) {
  25217. return;
  25218. }
  25219. this._animationTimeLast = now;
  25220. }
  25221. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25222. this._animationTime += deltaTime;
  25223. this._animationTimeLast = now;
  25224. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25225. this._activeAnimatables[index]._animate(this._animationTime);
  25226. }
  25227. // Late animation bindings
  25228. this._processLateAnimationBindings();
  25229. };
  25230. /** @ignore */
  25231. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25232. var target = runtimeAnimation.target;
  25233. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25234. if (!target._lateAnimationHolders) {
  25235. target._lateAnimationHolders = {};
  25236. }
  25237. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25238. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25239. totalWeight: 0,
  25240. animations: []
  25241. };
  25242. }
  25243. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25244. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25245. };
  25246. Scene.prototype._processLateAnimationBindings = function () {
  25247. if (!this._registeredForLateAnimationBindings.length) {
  25248. return;
  25249. }
  25250. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25251. var target = this._registeredForLateAnimationBindings.data[index];
  25252. for (var path in target._lateAnimationHolders) {
  25253. var holder = target._lateAnimationHolders[path];
  25254. var originalValue = holder.animations[0].originalValue;
  25255. // Sanity check
  25256. if (!originalValue.scaleAndAddToRef) {
  25257. continue;
  25258. }
  25259. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25260. var normalizer = 1.0;
  25261. var finalValue = void 0;
  25262. if (holder.totalWeight < 1.0) {
  25263. // We need to mix the original value in
  25264. if (matrixDecomposeMode) {
  25265. finalValue = originalValue.clone();
  25266. }
  25267. else {
  25268. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25269. }
  25270. }
  25271. else {
  25272. // We need to normalize the weights
  25273. normalizer = holder.totalWeight;
  25274. }
  25275. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25276. var runtimeAnimation = holder.animations[animIndex];
  25277. var scale = runtimeAnimation.weight / normalizer;
  25278. if (finalValue) {
  25279. if (matrixDecomposeMode) {
  25280. BABYLON.Matrix.DecomposeLerpToRef(finalValue, runtimeAnimation.currentValue, scale, finalValue);
  25281. }
  25282. else {
  25283. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25284. }
  25285. }
  25286. else {
  25287. if (scale !== 1) {
  25288. if (matrixDecomposeMode) {
  25289. finalValue = runtimeAnimation.currentValue.clone();
  25290. }
  25291. else {
  25292. finalValue = runtimeAnimation.currentValue.scale(scale);
  25293. }
  25294. }
  25295. else {
  25296. finalValue = runtimeAnimation.currentValue;
  25297. }
  25298. }
  25299. }
  25300. runtimeAnimation.target[path] = finalValue;
  25301. }
  25302. target._lateAnimationHolders = {};
  25303. }
  25304. this._registeredForLateAnimationBindings.reset();
  25305. };
  25306. // Matrix
  25307. /** @ignore */
  25308. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25309. this._useAlternateCameraConfiguration = active;
  25310. };
  25311. /**
  25312. * Gets the current view matrix
  25313. * @returns a Matrix
  25314. */
  25315. Scene.prototype.getViewMatrix = function () {
  25316. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25317. };
  25318. /**
  25319. * Gets the current projection matrix
  25320. * @returns a Matrix
  25321. */
  25322. Scene.prototype.getProjectionMatrix = function () {
  25323. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25324. };
  25325. /**
  25326. * Gets the current transform matrix
  25327. * @returns a Matrix made of View * Projection
  25328. */
  25329. Scene.prototype.getTransformMatrix = function () {
  25330. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25331. };
  25332. /**
  25333. * Sets the current transform matrix
  25334. * @param view defines the View matrix to use
  25335. * @param projection defines the Projection matrix to use
  25336. */
  25337. Scene.prototype.setTransformMatrix = function (view, projection) {
  25338. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25339. return;
  25340. }
  25341. this._viewUpdateFlag = view.updateFlag;
  25342. this._projectionUpdateFlag = projection.updateFlag;
  25343. this._viewMatrix = view;
  25344. this._projectionMatrix = projection;
  25345. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25346. // Update frustum
  25347. if (!this._frustumPlanes) {
  25348. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25349. }
  25350. else {
  25351. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25352. }
  25353. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25354. var otherCamera = this.activeCamera._alternateCamera;
  25355. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25356. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25357. }
  25358. if (this._sceneUbo.useUbo) {
  25359. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25360. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25361. this._sceneUbo.update();
  25362. }
  25363. };
  25364. /** @ignore */
  25365. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25366. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25367. return;
  25368. }
  25369. this._alternateViewUpdateFlag = view.updateFlag;
  25370. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25371. this._alternateViewMatrix = view;
  25372. this._alternateProjectionMatrix = projection;
  25373. if (!this._alternateTransformMatrix) {
  25374. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25375. }
  25376. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25377. if (!this._alternateSceneUbo) {
  25378. this._createAlternateUbo();
  25379. }
  25380. if (this._alternateSceneUbo.useUbo) {
  25381. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25382. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25383. this._alternateSceneUbo.update();
  25384. }
  25385. };
  25386. /**
  25387. * Gets the uniform buffer used to store scene data
  25388. * @returns a UniformBuffer
  25389. */
  25390. Scene.prototype.getSceneUniformBuffer = function () {
  25391. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25392. };
  25393. /**
  25394. * Gets an unique (relatively to the current scene) Id
  25395. * @returns an unique number for the scene
  25396. */
  25397. Scene.prototype.getUniqueId = function () {
  25398. var result = Scene._uniqueIdCounter;
  25399. Scene._uniqueIdCounter++;
  25400. return result;
  25401. };
  25402. /**
  25403. * Add a mesh to the list of scene's meshes
  25404. * @param newMesh defines the mesh to add
  25405. */
  25406. Scene.prototype.addMesh = function (newMesh) {
  25407. this.meshes.push(newMesh);
  25408. //notify the collision coordinator
  25409. if (this.collisionCoordinator) {
  25410. this.collisionCoordinator.onMeshAdded(newMesh);
  25411. }
  25412. newMesh._resyncLightSources();
  25413. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25414. };
  25415. /**
  25416. * Remove a mesh for the list of scene's meshes
  25417. * @param toRemove defines the mesh to remove
  25418. * @returns the index where the mesh was in the mesh list
  25419. */
  25420. Scene.prototype.removeMesh = function (toRemove) {
  25421. var index = this.meshes.indexOf(toRemove);
  25422. if (index !== -1) {
  25423. // Remove from the scene if mesh found
  25424. this.meshes.splice(index, 1);
  25425. }
  25426. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25427. return index;
  25428. };
  25429. /**
  25430. * Add a transform node to the list of scene's transform nodes
  25431. * @param newTransformNode defines the transform node to add
  25432. */
  25433. Scene.prototype.addTransformNode = function (newTransformNode) {
  25434. this.transformNodes.push(newTransformNode);
  25435. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25436. };
  25437. /**
  25438. * Remove a transform node for the list of scene's transform nodes
  25439. * @param toRemove defines the transform node to remove
  25440. * @returns the index where the transform node was in the transform node list
  25441. */
  25442. Scene.prototype.removeTransformNode = function (toRemove) {
  25443. var index = this.transformNodes.indexOf(toRemove);
  25444. if (index !== -1) {
  25445. // Remove from the scene if found
  25446. this.transformNodes.splice(index, 1);
  25447. }
  25448. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25449. return index;
  25450. };
  25451. /**
  25452. * Remove a skeleton for the list of scene's skeletons
  25453. * @param toRemove defines the skeleton to remove
  25454. * @returns the index where the skeleton was in the skeleton list
  25455. */
  25456. Scene.prototype.removeSkeleton = function (toRemove) {
  25457. var index = this.skeletons.indexOf(toRemove);
  25458. if (index !== -1) {
  25459. // Remove from the scene if found
  25460. this.skeletons.splice(index, 1);
  25461. }
  25462. return index;
  25463. };
  25464. /**
  25465. * Remove a morph target for the list of scene's morph targets
  25466. * @param toRemove defines the morph target to remove
  25467. * @returns the index where the morph target was in the morph target list
  25468. */
  25469. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25470. var index = this.morphTargetManagers.indexOf(toRemove);
  25471. if (index !== -1) {
  25472. // Remove from the scene if found
  25473. this.morphTargetManagers.splice(index, 1);
  25474. }
  25475. return index;
  25476. };
  25477. /**
  25478. * Remove a light for the list of scene's lights
  25479. * @param toRemove defines the light to remove
  25480. * @returns the index where the light was in the light list
  25481. */
  25482. Scene.prototype.removeLight = function (toRemove) {
  25483. var index = this.lights.indexOf(toRemove);
  25484. if (index !== -1) {
  25485. // Remove from meshes
  25486. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25487. var mesh = _a[_i];
  25488. mesh._removeLightSource(toRemove);
  25489. }
  25490. // Remove from the scene if mesh found
  25491. this.lights.splice(index, 1);
  25492. this.sortLightsByPriority();
  25493. }
  25494. this.onLightRemovedObservable.notifyObservers(toRemove);
  25495. return index;
  25496. };
  25497. /**
  25498. * Remove a camera for the list of scene's cameras
  25499. * @param toRemove defines the camera to remove
  25500. * @returns the index where the camera was in the camera list
  25501. */
  25502. Scene.prototype.removeCamera = function (toRemove) {
  25503. var index = this.cameras.indexOf(toRemove);
  25504. if (index !== -1) {
  25505. // Remove from the scene if mesh found
  25506. this.cameras.splice(index, 1);
  25507. }
  25508. // Remove from activeCameras
  25509. var index2 = this.activeCameras.indexOf(toRemove);
  25510. if (index2 !== -1) {
  25511. // Remove from the scene if mesh found
  25512. this.activeCameras.splice(index2, 1);
  25513. }
  25514. // Reset the activeCamera
  25515. if (this.activeCamera === toRemove) {
  25516. if (this.cameras.length > 0) {
  25517. this.activeCamera = this.cameras[0];
  25518. }
  25519. else {
  25520. this.activeCamera = null;
  25521. }
  25522. }
  25523. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25524. return index;
  25525. };
  25526. /**
  25527. * Remove a particle system for the list of scene's particle systems
  25528. * @param toRemove defines the particle system to remove
  25529. * @returns the index where the particle system was in the particle system list
  25530. */
  25531. Scene.prototype.removeParticleSystem = function (toRemove) {
  25532. var index = this.particleSystems.indexOf(toRemove);
  25533. if (index !== -1) {
  25534. this.particleSystems.splice(index, 1);
  25535. }
  25536. return index;
  25537. };
  25538. /**
  25539. * Remove a animation for the list of scene's animations
  25540. * @param toRemove defines the animation to remove
  25541. * @returns the index where the animation was in the animation list
  25542. */
  25543. Scene.prototype.removeAnimation = function (toRemove) {
  25544. var index = this.animations.indexOf(toRemove);
  25545. if (index !== -1) {
  25546. this.animations.splice(index, 1);
  25547. }
  25548. return index;
  25549. };
  25550. /**
  25551. * Removes the given animation group from this scene.
  25552. * @param toRemove The animation group to remove
  25553. * @returns The index of the removed animation group
  25554. */
  25555. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25556. var index = this.animationGroups.indexOf(toRemove);
  25557. if (index !== -1) {
  25558. this.animationGroups.splice(index, 1);
  25559. }
  25560. return index;
  25561. };
  25562. /**
  25563. * Removes the given multi-material from this scene.
  25564. * @param toRemove The multi-material to remove
  25565. * @returns The index of the removed multi-material
  25566. */
  25567. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25568. var index = this.multiMaterials.indexOf(toRemove);
  25569. if (index !== -1) {
  25570. this.multiMaterials.splice(index, 1);
  25571. }
  25572. return index;
  25573. };
  25574. /**
  25575. * Removes the given material from this scene.
  25576. * @param toRemove The material to remove
  25577. * @returns The index of the removed material
  25578. */
  25579. Scene.prototype.removeMaterial = function (toRemove) {
  25580. var index = this.materials.indexOf(toRemove);
  25581. if (index !== -1) {
  25582. this.materials.splice(index, 1);
  25583. }
  25584. return index;
  25585. };
  25586. /**
  25587. * Removes the given lens flare system from this scene.
  25588. * @param toRemove The lens flare system to remove
  25589. * @returns The index of the removed lens flare system
  25590. */
  25591. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25592. var index = this.lensFlareSystems.indexOf(toRemove);
  25593. if (index !== -1) {
  25594. this.lensFlareSystems.splice(index, 1);
  25595. }
  25596. return index;
  25597. };
  25598. /**
  25599. * Removes the given action manager from this scene.
  25600. * @param toRemove The action manager to remove
  25601. * @returns The index of the removed action manager
  25602. */
  25603. Scene.prototype.removeActionManager = function (toRemove) {
  25604. var index = this._actionManagers.indexOf(toRemove);
  25605. if (index !== -1) {
  25606. this._actionManagers.splice(index, 1);
  25607. }
  25608. return index;
  25609. };
  25610. /**
  25611. * Removes the given effect layer from this scene.
  25612. * @param toRemove defines the effect layer to remove
  25613. * @returns the index of the removed effect layer
  25614. */
  25615. Scene.prototype.removeEffectLayer = function (toRemove) {
  25616. var index = this.effectLayers.indexOf(toRemove);
  25617. if (index !== -1) {
  25618. this.effectLayers.splice(index, 1);
  25619. }
  25620. return index;
  25621. };
  25622. /**
  25623. * Removes the given texture from this scene.
  25624. * @param toRemove The texture to remove
  25625. * @returns The index of the removed texture
  25626. */
  25627. Scene.prototype.removeTexture = function (toRemove) {
  25628. var index = this.textures.indexOf(toRemove);
  25629. if (index !== -1) {
  25630. this.textures.splice(index, 1);
  25631. }
  25632. return index;
  25633. };
  25634. /**
  25635. * Adds the given light to this scene
  25636. * @param newLight The light to add
  25637. */
  25638. Scene.prototype.addLight = function (newLight) {
  25639. this.lights.push(newLight);
  25640. this.sortLightsByPriority();
  25641. // Add light to all meshes (To support if the light is removed and then readded)
  25642. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25643. var mesh = _a[_i];
  25644. if (mesh._lightSources.indexOf(newLight) === -1) {
  25645. mesh._lightSources.push(newLight);
  25646. mesh._resyncLightSources();
  25647. }
  25648. }
  25649. this.onNewLightAddedObservable.notifyObservers(newLight);
  25650. };
  25651. /**
  25652. * Sorts the list list based on light priorities
  25653. */
  25654. Scene.prototype.sortLightsByPriority = function () {
  25655. if (this.requireLightSorting) {
  25656. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  25657. }
  25658. };
  25659. /**
  25660. * Adds the given camera to this scene
  25661. * @param newCamera The camera to add
  25662. */
  25663. Scene.prototype.addCamera = function (newCamera) {
  25664. this.cameras.push(newCamera);
  25665. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  25666. };
  25667. /**
  25668. * Adds the given skeleton to this scene
  25669. * @param newSkeleton The skeleton to add
  25670. */
  25671. Scene.prototype.addSkeleton = function (newSkeleton) {
  25672. this.skeletons.push(newSkeleton);
  25673. };
  25674. /**
  25675. * Adds the given particle system to this scene
  25676. * @param newParticleSystem The particle system to add
  25677. */
  25678. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  25679. this.particleSystems.push(newParticleSystem);
  25680. };
  25681. /**
  25682. * Adds the given animation to this scene
  25683. * @param newAnimation The animation to add
  25684. */
  25685. Scene.prototype.addAnimation = function (newAnimation) {
  25686. this.animations.push(newAnimation);
  25687. };
  25688. /**
  25689. * Adds the given animation group to this scene.
  25690. * @param newAnimationGroup The animation group to add
  25691. */
  25692. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  25693. this.animationGroups.push(newAnimationGroup);
  25694. };
  25695. /**
  25696. * Adds the given multi-material to this scene
  25697. * @param newMultiMaterial The multi-material to add
  25698. */
  25699. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  25700. this.multiMaterials.push(newMultiMaterial);
  25701. };
  25702. /**
  25703. * Adds the given material to this scene
  25704. * @param newMaterial The material to add
  25705. */
  25706. Scene.prototype.addMaterial = function (newMaterial) {
  25707. this.materials.push(newMaterial);
  25708. };
  25709. /**
  25710. * Adds the given morph target to this scene
  25711. * @param newMorphTargetManager The morph target to add
  25712. */
  25713. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  25714. this.morphTargetManagers.push(newMorphTargetManager);
  25715. };
  25716. /**
  25717. * Adds the given geometry to this scene
  25718. * @param newGeometry The geometry to add
  25719. */
  25720. Scene.prototype.addGeometry = function (newGeometry) {
  25721. this._geometries.push(newGeometry);
  25722. };
  25723. /**
  25724. * Adds the given lens flare system to this scene
  25725. * @param newLensFlareSystem The lens flare system to add
  25726. */
  25727. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  25728. this.lensFlareSystems.push(newLensFlareSystem);
  25729. };
  25730. /**
  25731. * Adds the given effect layer to this scene
  25732. * @param newEffectLayer defines the effect layer to add
  25733. */
  25734. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  25735. this.effectLayers.push(newEffectLayer);
  25736. };
  25737. /**
  25738. * Adds the given action manager to this scene
  25739. * @param newActionManager The action manager to add
  25740. */
  25741. Scene.prototype.addActionManager = function (newActionManager) {
  25742. this._actionManagers.push(newActionManager);
  25743. };
  25744. /**
  25745. * Adds the given texture to this scene.
  25746. * @param newTexture The texture to add
  25747. */
  25748. Scene.prototype.addTexture = function (newTexture) {
  25749. this.textures.push(newTexture);
  25750. };
  25751. /**
  25752. * Switch active camera
  25753. * @param newCamera defines the new active camera
  25754. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  25755. */
  25756. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  25757. if (attachControl === void 0) { attachControl = true; }
  25758. var canvas = this._engine.getRenderingCanvas();
  25759. if (!canvas) {
  25760. return;
  25761. }
  25762. if (this.activeCamera) {
  25763. this.activeCamera.detachControl(canvas);
  25764. }
  25765. this.activeCamera = newCamera;
  25766. if (attachControl) {
  25767. newCamera.attachControl(canvas);
  25768. }
  25769. };
  25770. /**
  25771. * sets the active camera of the scene using its ID
  25772. * @param id defines the camera's ID
  25773. * @return the new active camera or null if none found.
  25774. */
  25775. Scene.prototype.setActiveCameraByID = function (id) {
  25776. var camera = this.getCameraByID(id);
  25777. if (camera) {
  25778. this.activeCamera = camera;
  25779. return camera;
  25780. }
  25781. return null;
  25782. };
  25783. /**
  25784. * sets the active camera of the scene using its name
  25785. * @param name defines the camera's name
  25786. * @returns the new active camera or null if none found.
  25787. */
  25788. Scene.prototype.setActiveCameraByName = function (name) {
  25789. var camera = this.getCameraByName(name);
  25790. if (camera) {
  25791. this.activeCamera = camera;
  25792. return camera;
  25793. }
  25794. return null;
  25795. };
  25796. /**
  25797. * get an animation group using its name
  25798. * @param name defines the material's name
  25799. * @return the animation group or null if none found.
  25800. */
  25801. Scene.prototype.getAnimationGroupByName = function (name) {
  25802. for (var index = 0; index < this.animationGroups.length; index++) {
  25803. if (this.animationGroups[index].name === name) {
  25804. return this.animationGroups[index];
  25805. }
  25806. }
  25807. return null;
  25808. };
  25809. /**
  25810. * get a material using its id
  25811. * @param id defines the material's ID
  25812. * @return the material or null if none found.
  25813. */
  25814. Scene.prototype.getMaterialByID = function (id) {
  25815. for (var index = 0; index < this.materials.length; index++) {
  25816. if (this.materials[index].id === id) {
  25817. return this.materials[index];
  25818. }
  25819. }
  25820. return null;
  25821. };
  25822. /**
  25823. * Gets a material using its name
  25824. * @param name defines the material's name
  25825. * @return the material or null if none found.
  25826. */
  25827. Scene.prototype.getMaterialByName = function (name) {
  25828. for (var index = 0; index < this.materials.length; index++) {
  25829. if (this.materials[index].name === name) {
  25830. return this.materials[index];
  25831. }
  25832. }
  25833. return null;
  25834. };
  25835. /**
  25836. * Gets a lens flare system using its name
  25837. * @param name defines the name to look for
  25838. * @returns the lens flare system or null if not found
  25839. */
  25840. Scene.prototype.getLensFlareSystemByName = function (name) {
  25841. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25842. if (this.lensFlareSystems[index].name === name) {
  25843. return this.lensFlareSystems[index];
  25844. }
  25845. }
  25846. return null;
  25847. };
  25848. /**
  25849. * Gets a lens flare system using its id
  25850. * @param id defines the id to look for
  25851. * @returns the lens flare system or null if not found
  25852. */
  25853. Scene.prototype.getLensFlareSystemByID = function (id) {
  25854. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25855. if (this.lensFlareSystems[index].id === id) {
  25856. return this.lensFlareSystems[index];
  25857. }
  25858. }
  25859. return null;
  25860. };
  25861. /**
  25862. * Gets a camera using its id
  25863. * @param id defines the id to look for
  25864. * @returns the camera or null if not found
  25865. */
  25866. Scene.prototype.getCameraByID = function (id) {
  25867. for (var index = 0; index < this.cameras.length; index++) {
  25868. if (this.cameras[index].id === id) {
  25869. return this.cameras[index];
  25870. }
  25871. }
  25872. return null;
  25873. };
  25874. /**
  25875. * Gets a camera using its unique id
  25876. * @param uniqueId defines the unique id to look for
  25877. * @returns the camera or null if not found
  25878. */
  25879. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  25880. for (var index = 0; index < this.cameras.length; index++) {
  25881. if (this.cameras[index].uniqueId === uniqueId) {
  25882. return this.cameras[index];
  25883. }
  25884. }
  25885. return null;
  25886. };
  25887. /**
  25888. * Gets a camera using its name
  25889. * @param name defines the camera's name
  25890. * @return the camera or null if none found.
  25891. */
  25892. Scene.prototype.getCameraByName = function (name) {
  25893. for (var index = 0; index < this.cameras.length; index++) {
  25894. if (this.cameras[index].name === name) {
  25895. return this.cameras[index];
  25896. }
  25897. }
  25898. return null;
  25899. };
  25900. /**
  25901. * Gets a bone using its id
  25902. * @param id defines the bone's id
  25903. * @return the bone or null if not found
  25904. */
  25905. Scene.prototype.getBoneByID = function (id) {
  25906. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25907. var skeleton = this.skeletons[skeletonIndex];
  25908. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25909. if (skeleton.bones[boneIndex].id === id) {
  25910. return skeleton.bones[boneIndex];
  25911. }
  25912. }
  25913. }
  25914. return null;
  25915. };
  25916. /**
  25917. * Gets a bone using its id
  25918. * @param name defines the bone's name
  25919. * @return the bone or null if not found
  25920. */
  25921. Scene.prototype.getBoneByName = function (name) {
  25922. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25923. var skeleton = this.skeletons[skeletonIndex];
  25924. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25925. if (skeleton.bones[boneIndex].name === name) {
  25926. return skeleton.bones[boneIndex];
  25927. }
  25928. }
  25929. }
  25930. return null;
  25931. };
  25932. /**
  25933. * Gets a light node using its name
  25934. * @param name defines the the light's name
  25935. * @return the light or null if none found.
  25936. */
  25937. Scene.prototype.getLightByName = function (name) {
  25938. for (var index = 0; index < this.lights.length; index++) {
  25939. if (this.lights[index].name === name) {
  25940. return this.lights[index];
  25941. }
  25942. }
  25943. return null;
  25944. };
  25945. /**
  25946. * Gets a light node using its id
  25947. * @param id defines the light's id
  25948. * @return the light or null if none found.
  25949. */
  25950. Scene.prototype.getLightByID = function (id) {
  25951. for (var index = 0; index < this.lights.length; index++) {
  25952. if (this.lights[index].id === id) {
  25953. return this.lights[index];
  25954. }
  25955. }
  25956. return null;
  25957. };
  25958. /**
  25959. * Gets a light node using its scene-generated unique ID
  25960. * @param uniqueId defines the light's unique id
  25961. * @return the light or null if none found.
  25962. */
  25963. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  25964. for (var index = 0; index < this.lights.length; index++) {
  25965. if (this.lights[index].uniqueId === uniqueId) {
  25966. return this.lights[index];
  25967. }
  25968. }
  25969. return null;
  25970. };
  25971. /**
  25972. * Gets a particle system by id
  25973. * @param id defines the particle system id
  25974. * @return the corresponding system or null if none found
  25975. */
  25976. Scene.prototype.getParticleSystemByID = function (id) {
  25977. for (var index = 0; index < this.particleSystems.length; index++) {
  25978. if (this.particleSystems[index].id === id) {
  25979. return this.particleSystems[index];
  25980. }
  25981. }
  25982. return null;
  25983. };
  25984. /**
  25985. * Gets a geometry using its ID
  25986. * @param id defines the geometry's id
  25987. * @return the geometry or null if none found.
  25988. */
  25989. Scene.prototype.getGeometryByID = function (id) {
  25990. for (var index = 0; index < this._geometries.length; index++) {
  25991. if (this._geometries[index].id === id) {
  25992. return this._geometries[index];
  25993. }
  25994. }
  25995. return null;
  25996. };
  25997. /**
  25998. * Add a new geometry to this scene
  25999. * @param geometry defines the geometry to be added to the scene.
  26000. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26001. * @return a boolean defining if the geometry was added or not
  26002. */
  26003. Scene.prototype.pushGeometry = function (geometry, force) {
  26004. if (!force && this.getGeometryByID(geometry.id)) {
  26005. return false;
  26006. }
  26007. this._geometries.push(geometry);
  26008. //notify the collision coordinator
  26009. if (this.collisionCoordinator) {
  26010. this.collisionCoordinator.onGeometryAdded(geometry);
  26011. }
  26012. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26013. return true;
  26014. };
  26015. /**
  26016. * Removes an existing geometry
  26017. * @param geometry defines the geometry to be removed from the scene
  26018. * @return a boolean defining if the geometry was removed or not
  26019. */
  26020. Scene.prototype.removeGeometry = function (geometry) {
  26021. var index = this._geometries.indexOf(geometry);
  26022. if (index > -1) {
  26023. this._geometries.splice(index, 1);
  26024. //notify the collision coordinator
  26025. if (this.collisionCoordinator) {
  26026. this.collisionCoordinator.onGeometryDeleted(geometry);
  26027. }
  26028. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26029. return true;
  26030. }
  26031. return false;
  26032. };
  26033. /**
  26034. * Gets the list of geometries attached to the scene
  26035. * @returns an array of Geometry
  26036. */
  26037. Scene.prototype.getGeometries = function () {
  26038. return this._geometries;
  26039. };
  26040. /**
  26041. * Gets the first added mesh found of a given ID
  26042. * @param id defines the id to search for
  26043. * @return the mesh found or null if not found at all
  26044. */
  26045. Scene.prototype.getMeshByID = function (id) {
  26046. for (var index = 0; index < this.meshes.length; index++) {
  26047. if (this.meshes[index].id === id) {
  26048. return this.meshes[index];
  26049. }
  26050. }
  26051. return null;
  26052. };
  26053. /**
  26054. * Gets a list of meshes using their id
  26055. * @param id defines the id to search for
  26056. * @returns a list of meshes
  26057. */
  26058. Scene.prototype.getMeshesByID = function (id) {
  26059. return this.meshes.filter(function (m) {
  26060. return m.id === id;
  26061. });
  26062. };
  26063. /**
  26064. * Gets the first added transform node found of a given ID
  26065. * @param id defines the id to search for
  26066. * @return the found transform node or null if not found at all.
  26067. */
  26068. Scene.prototype.getTransformNodeByID = function (id) {
  26069. for (var index = 0; index < this.transformNodes.length; index++) {
  26070. if (this.transformNodes[index].id === id) {
  26071. return this.transformNodes[index];
  26072. }
  26073. }
  26074. return null;
  26075. };
  26076. /**
  26077. * Gets a list of transform nodes using their id
  26078. * @param id defines the id to search for
  26079. * @returns a list of transform nodes
  26080. */
  26081. Scene.prototype.getTransformNodesByID = function (id) {
  26082. return this.transformNodes.filter(function (m) {
  26083. return m.id === id;
  26084. });
  26085. };
  26086. /**
  26087. * Gets a mesh with its auto-generated unique id
  26088. * @param uniqueId defines the unique id to search for
  26089. * @return the found mesh or null if not found at all.
  26090. */
  26091. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26092. for (var index = 0; index < this.meshes.length; index++) {
  26093. if (this.meshes[index].uniqueId === uniqueId) {
  26094. return this.meshes[index];
  26095. }
  26096. }
  26097. return null;
  26098. };
  26099. /**
  26100. * Gets a the last added mesh using a given id
  26101. * @param id defines the id to search for
  26102. * @return the found mesh or null if not found at all.
  26103. */
  26104. Scene.prototype.getLastMeshByID = function (id) {
  26105. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26106. if (this.meshes[index].id === id) {
  26107. return this.meshes[index];
  26108. }
  26109. }
  26110. return null;
  26111. };
  26112. /**
  26113. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26114. * @param id defines the id to search for
  26115. * @return the found node or null if not found at all
  26116. */
  26117. Scene.prototype.getLastEntryByID = function (id) {
  26118. var index;
  26119. for (index = this.meshes.length - 1; index >= 0; index--) {
  26120. if (this.meshes[index].id === id) {
  26121. return this.meshes[index];
  26122. }
  26123. }
  26124. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26125. if (this.transformNodes[index].id === id) {
  26126. return this.transformNodes[index];
  26127. }
  26128. }
  26129. for (index = this.cameras.length - 1; index >= 0; index--) {
  26130. if (this.cameras[index].id === id) {
  26131. return this.cameras[index];
  26132. }
  26133. }
  26134. for (index = this.lights.length - 1; index >= 0; index--) {
  26135. if (this.lights[index].id === id) {
  26136. return this.lights[index];
  26137. }
  26138. }
  26139. return null;
  26140. };
  26141. /**
  26142. * Gets a node (Mesh, Camera, Light) using a given id
  26143. * @param id defines the id to search for
  26144. * @return the found node or null if not found at all
  26145. */
  26146. Scene.prototype.getNodeByID = function (id) {
  26147. var mesh = this.getMeshByID(id);
  26148. if (mesh) {
  26149. return mesh;
  26150. }
  26151. var light = this.getLightByID(id);
  26152. if (light) {
  26153. return light;
  26154. }
  26155. var camera = this.getCameraByID(id);
  26156. if (camera) {
  26157. return camera;
  26158. }
  26159. var bone = this.getBoneByID(id);
  26160. return bone;
  26161. };
  26162. /**
  26163. * Gets a node (Mesh, Camera, Light) using a given name
  26164. * @param name defines the name to search for
  26165. * @return the found node or null if not found at all.
  26166. */
  26167. Scene.prototype.getNodeByName = function (name) {
  26168. var mesh = this.getMeshByName(name);
  26169. if (mesh) {
  26170. return mesh;
  26171. }
  26172. var light = this.getLightByName(name);
  26173. if (light) {
  26174. return light;
  26175. }
  26176. var camera = this.getCameraByName(name);
  26177. if (camera) {
  26178. return camera;
  26179. }
  26180. var bone = this.getBoneByName(name);
  26181. return bone;
  26182. };
  26183. /**
  26184. * Gets a mesh using a given name
  26185. * @param name defines the name to search for
  26186. * @return the found mesh or null if not found at all.
  26187. */
  26188. Scene.prototype.getMeshByName = function (name) {
  26189. for (var index = 0; index < this.meshes.length; index++) {
  26190. if (this.meshes[index].name === name) {
  26191. return this.meshes[index];
  26192. }
  26193. }
  26194. return null;
  26195. };
  26196. /**
  26197. * Gets a transform node using a given name
  26198. * @param name defines the name to search for
  26199. * @return the found transform node or null if not found at all.
  26200. */
  26201. Scene.prototype.getTransformNodeByName = function (name) {
  26202. for (var index = 0; index < this.transformNodes.length; index++) {
  26203. if (this.transformNodes[index].name === name) {
  26204. return this.transformNodes[index];
  26205. }
  26206. }
  26207. return null;
  26208. };
  26209. /**
  26210. * Gets a sound using a given name
  26211. * @param name defines the name to search for
  26212. * @return the found sound or null if not found at all.
  26213. */
  26214. Scene.prototype.getSoundByName = function (name) {
  26215. var index;
  26216. if (BABYLON.AudioEngine) {
  26217. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26218. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26219. return this.mainSoundTrack.soundCollection[index];
  26220. }
  26221. }
  26222. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26223. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26224. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26225. return this.soundTracks[sdIndex].soundCollection[index];
  26226. }
  26227. }
  26228. }
  26229. }
  26230. return null;
  26231. };
  26232. /**
  26233. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26234. * @param id defines the id to search for
  26235. * @return the found skeleton or null if not found at all.
  26236. */
  26237. Scene.prototype.getLastSkeletonByID = function (id) {
  26238. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26239. if (this.skeletons[index].id === id) {
  26240. return this.skeletons[index];
  26241. }
  26242. }
  26243. return null;
  26244. };
  26245. /**
  26246. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26247. * @param id defines the id to search for
  26248. * @return the found skeleton or null if not found at all.
  26249. */
  26250. Scene.prototype.getSkeletonById = function (id) {
  26251. for (var index = 0; index < this.skeletons.length; index++) {
  26252. if (this.skeletons[index].id === id) {
  26253. return this.skeletons[index];
  26254. }
  26255. }
  26256. return null;
  26257. };
  26258. /**
  26259. * Gets a skeleton using a given name
  26260. * @param name defines the name to search for
  26261. * @return the found skeleton or null if not found at all.
  26262. */
  26263. Scene.prototype.getSkeletonByName = function (name) {
  26264. for (var index = 0; index < this.skeletons.length; index++) {
  26265. if (this.skeletons[index].name === name) {
  26266. return this.skeletons[index];
  26267. }
  26268. }
  26269. return null;
  26270. };
  26271. /**
  26272. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26273. * @param id defines the id to search for
  26274. * @return the found morph target manager or null if not found at all.
  26275. */
  26276. Scene.prototype.getMorphTargetManagerById = function (id) {
  26277. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26278. if (this.morphTargetManagers[index].uniqueId === id) {
  26279. return this.morphTargetManagers[index];
  26280. }
  26281. }
  26282. return null;
  26283. };
  26284. /**
  26285. * Gets a boolean indicating if the given mesh is active
  26286. * @param mesh defines the mesh to look for
  26287. * @returns true if the mesh is in the active list
  26288. */
  26289. Scene.prototype.isActiveMesh = function (mesh) {
  26290. return (this._activeMeshes.indexOf(mesh) !== -1);
  26291. };
  26292. /**
  26293. * Return a the first highlight layer of the scene with a given name.
  26294. * @param name The name of the highlight layer to look for.
  26295. * @return The highlight layer if found otherwise null.
  26296. */
  26297. Scene.prototype.getHighlightLayerByName = function (name) {
  26298. for (var index = 0; index < this.effectLayers.length; index++) {
  26299. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26300. return this.effectLayers[index];
  26301. }
  26302. }
  26303. return null;
  26304. };
  26305. /**
  26306. * Return a the first highlight layer of the scene with a given name.
  26307. * @param name The name of the highlight layer to look for.
  26308. * @return The highlight layer if found otherwise null.
  26309. */
  26310. Scene.prototype.getGlowLayerByName = function (name) {
  26311. for (var index = 0; index < this.effectLayers.length; index++) {
  26312. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26313. return this.effectLayers[index];
  26314. }
  26315. }
  26316. return null;
  26317. };
  26318. Object.defineProperty(Scene.prototype, "uid", {
  26319. /**
  26320. * Return a unique id as a string which can serve as an identifier for the scene
  26321. */
  26322. get: function () {
  26323. if (!this._uid) {
  26324. this._uid = BABYLON.Tools.RandomId();
  26325. }
  26326. return this._uid;
  26327. },
  26328. enumerable: true,
  26329. configurable: true
  26330. });
  26331. /**
  26332. * Add an externaly attached data from its key.
  26333. * This method call will fail and return false, if such key already exists.
  26334. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26335. * @param key the unique key that identifies the data
  26336. * @param data the data object to associate to the key for this Engine instance
  26337. * @return true if no such key were already present and the data was added successfully, false otherwise
  26338. */
  26339. Scene.prototype.addExternalData = function (key, data) {
  26340. if (!this._externalData) {
  26341. this._externalData = new BABYLON.StringDictionary();
  26342. }
  26343. return this._externalData.add(key, data);
  26344. };
  26345. /**
  26346. * Get an externaly attached data from its key
  26347. * @param key the unique key that identifies the data
  26348. * @return the associated data, if present (can be null), or undefined if not present
  26349. */
  26350. Scene.prototype.getExternalData = function (key) {
  26351. if (!this._externalData) {
  26352. return null;
  26353. }
  26354. return this._externalData.get(key);
  26355. };
  26356. /**
  26357. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26358. * @param key the unique key that identifies the data
  26359. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26360. * @return the associated data, can be null if the factory returned null.
  26361. */
  26362. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26363. if (!this._externalData) {
  26364. this._externalData = new BABYLON.StringDictionary();
  26365. }
  26366. return this._externalData.getOrAddWithFactory(key, factory);
  26367. };
  26368. /**
  26369. * Remove an externaly attached data from the Engine instance
  26370. * @param key the unique key that identifies the data
  26371. * @return true if the data was successfully removed, false if it doesn't exist
  26372. */
  26373. Scene.prototype.removeExternalData = function (key) {
  26374. return this._externalData.remove(key);
  26375. };
  26376. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26377. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26378. if (mesh.showSubMeshesBoundingBox) {
  26379. var boundingInfo = subMesh.getBoundingInfo();
  26380. if (boundingInfo !== null && boundingInfo !== undefined) {
  26381. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26382. }
  26383. }
  26384. var material = subMesh.getMaterial();
  26385. if (material !== null && material !== undefined) {
  26386. // Render targets
  26387. if (material.getRenderTargetTextures !== undefined) {
  26388. if (this._processedMaterials.indexOf(material) === -1) {
  26389. this._processedMaterials.push(material);
  26390. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26391. }
  26392. }
  26393. // Dispatch
  26394. this._activeIndices.addCount(subMesh.indexCount, false);
  26395. this._renderingManager.dispatch(subMesh, mesh, material);
  26396. }
  26397. }
  26398. };
  26399. /**
  26400. * Clear the processed materials smart array preventing retention point in material dispose.
  26401. */
  26402. Scene.prototype.freeProcessedMaterials = function () {
  26403. this._processedMaterials.dispose();
  26404. };
  26405. /**
  26406. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26407. */
  26408. Scene.prototype.freeActiveMeshes = function () {
  26409. this._activeMeshes.dispose();
  26410. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26411. this.activeCamera._activeMeshes.dispose();
  26412. }
  26413. if (this.activeCameras) {
  26414. for (var i = 0; i < this.activeCameras.length; i++) {
  26415. var activeCamera = this.activeCameras[i];
  26416. if (activeCamera && activeCamera._activeMeshes) {
  26417. activeCamera._activeMeshes.dispose();
  26418. }
  26419. }
  26420. }
  26421. };
  26422. /**
  26423. * Clear the info related to rendering groups preventing retention points during dispose.
  26424. */
  26425. Scene.prototype.freeRenderingGroups = function () {
  26426. if (this._renderingManager) {
  26427. this._renderingManager.freeRenderingGroups();
  26428. }
  26429. if (this.textures) {
  26430. for (var i = 0; i < this.textures.length; i++) {
  26431. var texture = this.textures[i];
  26432. if (texture && texture.renderList) {
  26433. texture.freeRenderingGroups();
  26434. }
  26435. }
  26436. }
  26437. };
  26438. /** @ignore */
  26439. Scene.prototype._isInIntermediateRendering = function () {
  26440. return this._intermediateRendering;
  26441. };
  26442. /**
  26443. * Defines the current active mesh candidate provider
  26444. * @param provider defines the provider to use
  26445. */
  26446. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26447. this._activeMeshCandidateProvider = provider;
  26448. };
  26449. /**
  26450. * Gets the current active mesh candidate provider
  26451. * @returns the current active mesh candidate provider
  26452. */
  26453. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26454. return this._activeMeshCandidateProvider;
  26455. };
  26456. /**
  26457. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26458. * @returns the current scene
  26459. */
  26460. Scene.prototype.freezeActiveMeshes = function () {
  26461. if (!this.activeCamera) {
  26462. return this;
  26463. }
  26464. if (!this._frustumPlanes) {
  26465. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26466. }
  26467. this._evaluateActiveMeshes();
  26468. this._activeMeshesFrozen = true;
  26469. return this;
  26470. };
  26471. /**
  26472. * Use this function to restart evaluating active meshes on every frame
  26473. * @returns the current scene
  26474. */
  26475. Scene.prototype.unfreezeActiveMeshes = function () {
  26476. this._activeMeshesFrozen = false;
  26477. return this;
  26478. };
  26479. Scene.prototype._evaluateActiveMeshes = function () {
  26480. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26481. return;
  26482. }
  26483. if (!this.activeCamera) {
  26484. return;
  26485. }
  26486. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26487. this.activeCamera._activeMeshes.reset();
  26488. this._activeMeshes.reset();
  26489. this._renderingManager.reset();
  26490. this._processedMaterials.reset();
  26491. this._activeParticleSystems.reset();
  26492. this._activeSkeletons.reset();
  26493. this._softwareSkinnedMeshes.reset();
  26494. if (this._boundingBoxRenderer) {
  26495. this._boundingBoxRenderer.reset();
  26496. }
  26497. // Meshes
  26498. var meshes;
  26499. var len;
  26500. var checkIsEnabled = true;
  26501. // Determine mesh candidates
  26502. if (this._activeMeshCandidateProvider !== undefined) {
  26503. // Use _activeMeshCandidateProvider
  26504. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26505. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26506. if (meshes !== undefined) {
  26507. len = meshes.length;
  26508. }
  26509. else {
  26510. len = 0;
  26511. }
  26512. }
  26513. else if (this._selectionOctree !== undefined) {
  26514. // Octree
  26515. var selection = this._selectionOctree.select(this._frustumPlanes);
  26516. meshes = selection.data;
  26517. len = selection.length;
  26518. }
  26519. else {
  26520. // Full scene traversal
  26521. len = this.meshes.length;
  26522. meshes = this.meshes;
  26523. }
  26524. // Check each mesh
  26525. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26526. mesh = meshes[meshIndex];
  26527. if (mesh.isBlocked) {
  26528. continue;
  26529. }
  26530. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26531. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26532. continue;
  26533. }
  26534. mesh.computeWorldMatrix();
  26535. // Intersections
  26536. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26537. this._meshesForIntersections.pushNoDuplicate(mesh);
  26538. }
  26539. // Switch to current LOD
  26540. meshLOD = mesh.getLOD(this.activeCamera);
  26541. if (meshLOD === undefined || meshLOD === null) {
  26542. continue;
  26543. }
  26544. mesh._preActivate();
  26545. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26546. this._activeMeshes.push(mesh);
  26547. this.activeCamera._activeMeshes.push(mesh);
  26548. mesh._activate(this._renderId);
  26549. if (meshLOD !== mesh) {
  26550. meshLOD._activate(this._renderId);
  26551. }
  26552. this._activeMesh(mesh, meshLOD);
  26553. }
  26554. }
  26555. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26556. // Particle systems
  26557. if (this.particlesEnabled) {
  26558. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26559. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26560. var particleSystem = this.particleSystems[particleIndex];
  26561. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26562. continue;
  26563. }
  26564. var emitter = particleSystem.emitter;
  26565. if (!emitter.position || emitter.isEnabled()) {
  26566. this._activeParticleSystems.push(particleSystem);
  26567. particleSystem.animate();
  26568. this._renderingManager.dispatchParticles(particleSystem);
  26569. }
  26570. }
  26571. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26572. }
  26573. };
  26574. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26575. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26576. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26577. mesh.skeleton.prepare();
  26578. }
  26579. if (!mesh.computeBonesUsingShaders) {
  26580. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26581. }
  26582. }
  26583. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26584. var boundingInfo = sourceMesh.getBoundingInfo();
  26585. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26586. }
  26587. if (mesh !== undefined && mesh !== null
  26588. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26589. // Submeshes Octrees
  26590. var len;
  26591. var subMeshes;
  26592. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26593. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26594. len = intersections.length;
  26595. subMeshes = intersections.data;
  26596. }
  26597. else {
  26598. subMeshes = mesh.subMeshes;
  26599. len = subMeshes.length;
  26600. }
  26601. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26602. subMesh = subMeshes[subIndex];
  26603. this._evaluateSubMesh(subMesh, mesh);
  26604. }
  26605. }
  26606. };
  26607. /**
  26608. * Update the transform matrix to update from the current active camera
  26609. * @param force defines a boolean used to force the update even if cache is up to date
  26610. */
  26611. Scene.prototype.updateTransformMatrix = function (force) {
  26612. if (!this.activeCamera) {
  26613. return;
  26614. }
  26615. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  26616. };
  26617. /**
  26618. * 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)
  26619. * @param alternateCamera defines the camera to use
  26620. */
  26621. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  26622. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  26623. };
  26624. Scene.prototype._renderForCamera = function (camera, rigParent) {
  26625. if (camera && camera._skipRendering) {
  26626. return;
  26627. }
  26628. var engine = this._engine;
  26629. this.activeCamera = camera;
  26630. if (!this.activeCamera)
  26631. throw new Error("Active camera not set");
  26632. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26633. // Viewport
  26634. engine.setViewport(this.activeCamera.viewport);
  26635. // Camera
  26636. this.resetCachedMaterial();
  26637. this._renderId++;
  26638. this.updateTransformMatrix();
  26639. if (camera._alternateCamera) {
  26640. this.updateAlternateTransformMatrix(camera._alternateCamera);
  26641. this._alternateRendering = true;
  26642. }
  26643. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  26644. // Meshes
  26645. this._evaluateActiveMeshes();
  26646. // Software skinning
  26647. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  26648. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  26649. mesh.applySkeleton(mesh.skeleton);
  26650. }
  26651. // Render targets
  26652. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26653. var needsRestoreFrameBuffer = false;
  26654. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  26655. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  26656. }
  26657. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  26658. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  26659. }
  26660. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  26661. this._intermediateRendering = true;
  26662. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26663. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  26664. var renderTarget = this._renderTargets.data[renderIndex];
  26665. if (renderTarget._shouldRender()) {
  26666. this._renderId++;
  26667. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  26668. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  26669. }
  26670. }
  26671. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26672. this._intermediateRendering = false;
  26673. this._renderId++;
  26674. needsRestoreFrameBuffer = true; // Restore back buffer
  26675. }
  26676. // Render EffecttLayer Texture
  26677. var stencilState = this._engine.getStencilBuffer();
  26678. var renderEffects = false;
  26679. var needStencil = false;
  26680. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  26681. this._intermediateRendering = true;
  26682. for (var i = 0; i < this.effectLayers.length; i++) {
  26683. var effectLayer = this.effectLayers[i];
  26684. if (effectLayer.shouldRender() &&
  26685. (!effectLayer.camera ||
  26686. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  26687. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  26688. renderEffects = true;
  26689. needStencil = needStencil || effectLayer.needStencil();
  26690. var renderTarget = effectLayer._mainTexture;
  26691. if (renderTarget._shouldRender()) {
  26692. this._renderId++;
  26693. renderTarget.render(false, false);
  26694. needsRestoreFrameBuffer = true;
  26695. }
  26696. }
  26697. }
  26698. this._intermediateRendering = false;
  26699. this._renderId++;
  26700. }
  26701. if (needsRestoreFrameBuffer) {
  26702. engine.restoreDefaultFramebuffer(); // Restore back buffer
  26703. }
  26704. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26705. // Prepare Frame
  26706. this.postProcessManager._prepareFrame();
  26707. // Backgrounds
  26708. var layerIndex;
  26709. var layer;
  26710. if (this.layers.length) {
  26711. engine.setDepthBuffer(false);
  26712. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26713. layer = this.layers[layerIndex];
  26714. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26715. layer.render();
  26716. }
  26717. }
  26718. engine.setDepthBuffer(true);
  26719. }
  26720. // Activate effect Layer stencil
  26721. if (needStencil) {
  26722. this._engine.setStencilBuffer(true);
  26723. }
  26724. // Render
  26725. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  26726. this._renderingManager.render(null, null, true, true);
  26727. this.onAfterDrawPhaseObservable.notifyObservers(this);
  26728. // Restore effect Layer stencil
  26729. if (needStencil) {
  26730. this._engine.setStencilBuffer(stencilState);
  26731. }
  26732. // Bounding boxes
  26733. if (this._boundingBoxRenderer) {
  26734. this._boundingBoxRenderer.render();
  26735. }
  26736. // Lens flares
  26737. if (this.lensFlaresEnabled) {
  26738. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26739. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  26740. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  26741. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  26742. lensFlareSystem.render();
  26743. }
  26744. }
  26745. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26746. }
  26747. // Effect Layer
  26748. if (renderEffects) {
  26749. engine.setDepthBuffer(false);
  26750. for (var i = 0; i < this.effectLayers.length; i++) {
  26751. if (this.effectLayers[i].shouldRender()) {
  26752. this.effectLayers[i].render();
  26753. }
  26754. }
  26755. engine.setDepthBuffer(true);
  26756. }
  26757. // Foregrounds
  26758. if (this.layers.length) {
  26759. engine.setDepthBuffer(false);
  26760. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26761. layer = this.layers[layerIndex];
  26762. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26763. layer.render();
  26764. }
  26765. }
  26766. engine.setDepthBuffer(true);
  26767. }
  26768. // Finalize frame
  26769. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  26770. // Reset some special arrays
  26771. this._renderTargets.reset();
  26772. this._alternateRendering = false;
  26773. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  26774. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26775. };
  26776. Scene.prototype._processSubCameras = function (camera) {
  26777. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  26778. this._renderForCamera(camera);
  26779. return;
  26780. }
  26781. // rig cameras
  26782. for (var index = 0; index < camera._rigCameras.length; index++) {
  26783. this._renderForCamera(camera._rigCameras[index], camera);
  26784. }
  26785. this.activeCamera = camera;
  26786. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26787. };
  26788. Scene.prototype._checkIntersections = function () {
  26789. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  26790. var sourceMesh = this._meshesForIntersections.data[index];
  26791. if (!sourceMesh.actionManager) {
  26792. continue;
  26793. }
  26794. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  26795. var action = sourceMesh.actionManager.actions[actionIndex];
  26796. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26797. var parameters = action.getTriggerParameter();
  26798. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  26799. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  26800. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  26801. if (areIntersecting && currentIntersectionInProgress === -1) {
  26802. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  26803. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26804. sourceMesh._intersectionsInProgress.push(otherMesh);
  26805. }
  26806. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26807. sourceMesh._intersectionsInProgress.push(otherMesh);
  26808. }
  26809. }
  26810. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  26811. //They intersected, and now they don't.
  26812. //is this trigger an exit trigger? execute an event.
  26813. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26814. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26815. }
  26816. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  26817. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  26818. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  26819. return otherMesh === parameterMesh;
  26820. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26821. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  26822. }
  26823. }
  26824. }
  26825. }
  26826. }
  26827. };
  26828. /**
  26829. * Render the scene
  26830. */
  26831. Scene.prototype.render = function () {
  26832. if (this.isDisposed) {
  26833. return;
  26834. }
  26835. this._activeParticles.fetchNewFrame();
  26836. this._totalVertices.fetchNewFrame();
  26837. this._activeIndices.fetchNewFrame();
  26838. this._activeBones.fetchNewFrame();
  26839. this._meshesForIntersections.reset();
  26840. this.resetCachedMaterial();
  26841. this.onBeforeAnimationsObservable.notifyObservers(this);
  26842. // Actions
  26843. if (this.actionManager) {
  26844. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  26845. }
  26846. //Simplification Queue
  26847. if (this.simplificationQueue && !this.simplificationQueue.running) {
  26848. this.simplificationQueue.executeNext();
  26849. }
  26850. if (this._engine.isDeterministicLockStep()) {
  26851. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  26852. var defaultFPS = (60.0 / 1000.0);
  26853. var defaultFrameTime = 1000 / 60; // frame time in MS
  26854. if (this._physicsEngine) {
  26855. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  26856. }
  26857. var stepsTaken = 0;
  26858. var maxSubSteps = this._engine.getLockstepMaxSteps();
  26859. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  26860. internalSteps = Math.min(internalSteps, maxSubSteps);
  26861. do {
  26862. this.onBeforeStepObservable.notifyObservers(this);
  26863. // Animations
  26864. this._animationRatio = defaultFrameTime * defaultFPS;
  26865. this._animate();
  26866. this.onAfterAnimationsObservable.notifyObservers(this);
  26867. // Physics
  26868. if (this._physicsEngine) {
  26869. this.onBeforePhysicsObservable.notifyObservers(this);
  26870. this._physicsEngine._step(defaultFrameTime / 1000);
  26871. this.onAfterPhysicsObservable.notifyObservers(this);
  26872. }
  26873. this.onAfterStepObservable.notifyObservers(this);
  26874. this._currentStepId++;
  26875. stepsTaken++;
  26876. deltaTime -= defaultFrameTime;
  26877. } while (deltaTime > 0 && stepsTaken < internalSteps);
  26878. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  26879. }
  26880. else {
  26881. // Animations
  26882. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  26883. this._animationRatio = deltaTime * (60.0 / 1000.0);
  26884. this._animate();
  26885. this.onAfterAnimationsObservable.notifyObservers(this);
  26886. // Physics
  26887. if (this._physicsEngine) {
  26888. this.onBeforePhysicsObservable.notifyObservers(this);
  26889. this._physicsEngine._step(deltaTime / 1000.0);
  26890. this.onAfterPhysicsObservable.notifyObservers(this);
  26891. }
  26892. }
  26893. // update gamepad manager
  26894. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  26895. this._gamepadManager._checkGamepadsStatus();
  26896. }
  26897. // Update Cameras
  26898. if (this.activeCameras.length > 0) {
  26899. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26900. var camera = this.activeCameras[cameraIndex];
  26901. camera.update();
  26902. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26903. // rig cameras
  26904. for (var index = 0; index < camera._rigCameras.length; index++) {
  26905. camera._rigCameras[index].update();
  26906. }
  26907. }
  26908. }
  26909. }
  26910. else if (this.activeCamera) {
  26911. this.activeCamera.update();
  26912. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26913. // rig cameras
  26914. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  26915. this.activeCamera._rigCameras[index].update();
  26916. }
  26917. }
  26918. }
  26919. // Before render
  26920. this.onBeforeRenderObservable.notifyObservers(this);
  26921. // Customs render targets
  26922. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26923. var engine = this.getEngine();
  26924. var currentActiveCamera = this.activeCamera;
  26925. if (this.renderTargetsEnabled) {
  26926. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  26927. this._intermediateRendering = true;
  26928. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  26929. var renderTarget = this.customRenderTargets[customIndex];
  26930. if (renderTarget._shouldRender()) {
  26931. this._renderId++;
  26932. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  26933. if (!this.activeCamera)
  26934. throw new Error("Active camera not set");
  26935. // Viewport
  26936. engine.setViewport(this.activeCamera.viewport);
  26937. // Camera
  26938. this.updateTransformMatrix();
  26939. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  26940. }
  26941. }
  26942. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  26943. this._intermediateRendering = false;
  26944. this._renderId++;
  26945. }
  26946. // Restore back buffer
  26947. if (this.customRenderTargets.length > 0) {
  26948. engine.restoreDefaultFramebuffer();
  26949. }
  26950. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26951. this.activeCamera = currentActiveCamera;
  26952. // Procedural textures
  26953. if (this.proceduralTexturesEnabled) {
  26954. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  26955. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  26956. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  26957. if (proceduralTexture._shouldRender()) {
  26958. proceduralTexture.render();
  26959. }
  26960. }
  26961. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  26962. }
  26963. // Clear
  26964. if (this.autoClearDepthAndStencil || this.autoClear) {
  26965. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  26966. }
  26967. // Shadows
  26968. if (this.shadowsEnabled) {
  26969. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  26970. var light = this.lights[lightIndex];
  26971. var shadowGenerator = light.getShadowGenerator();
  26972. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  26973. var shadowMap = (shadowGenerator.getShadowMap());
  26974. if (this.textures.indexOf(shadowMap) !== -1) {
  26975. this._renderTargets.push(shadowMap);
  26976. }
  26977. }
  26978. }
  26979. }
  26980. // Depth renderer
  26981. for (var key in this._depthRenderer) {
  26982. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  26983. }
  26984. // Geometry renderer
  26985. if (this._geometryBufferRenderer) {
  26986. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  26987. }
  26988. // RenderPipeline
  26989. if (this._postProcessRenderPipelineManager) {
  26990. this._postProcessRenderPipelineManager.update();
  26991. }
  26992. // Multi-cameras?
  26993. if (this.activeCameras.length > 0) {
  26994. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26995. if (cameraIndex > 0) {
  26996. this._engine.clear(null, false, true, true);
  26997. }
  26998. this._processSubCameras(this.activeCameras[cameraIndex]);
  26999. }
  27000. }
  27001. else {
  27002. if (!this.activeCamera) {
  27003. throw new Error("No camera defined");
  27004. }
  27005. this._processSubCameras(this.activeCamera);
  27006. }
  27007. // Intersection checks
  27008. this._checkIntersections();
  27009. // Update the audio listener attached to the camera
  27010. if (BABYLON.AudioEngine) {
  27011. this._updateAudioParameters();
  27012. }
  27013. // After render
  27014. if (this.afterRender) {
  27015. this.afterRender();
  27016. }
  27017. this.onAfterRenderObservable.notifyObservers(this);
  27018. // Cleaning
  27019. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27020. var data = this._toBeDisposed.data[index];
  27021. if (data) {
  27022. data.dispose();
  27023. }
  27024. this._toBeDisposed[index] = null;
  27025. }
  27026. this._toBeDisposed.reset();
  27027. if (this.dumpNextRenderTargets) {
  27028. this.dumpNextRenderTargets = false;
  27029. }
  27030. this._activeBones.addCount(0, true);
  27031. this._activeIndices.addCount(0, true);
  27032. this._activeParticles.addCount(0, true);
  27033. };
  27034. Scene.prototype._updateAudioParameters = function () {
  27035. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27036. return;
  27037. }
  27038. var listeningCamera;
  27039. var audioEngine = BABYLON.Engine.audioEngine;
  27040. if (this.activeCameras.length > 0) {
  27041. listeningCamera = this.activeCameras[0];
  27042. }
  27043. else {
  27044. listeningCamera = this.activeCamera;
  27045. }
  27046. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27047. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27048. // for VR cameras
  27049. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27050. listeningCamera = listeningCamera.rigCameras[0];
  27051. }
  27052. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27053. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27054. cameraDirection.normalize();
  27055. // To avoid some errors on GearVR
  27056. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27057. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27058. }
  27059. var i;
  27060. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27061. var sound = this.mainSoundTrack.soundCollection[i];
  27062. if (sound.useCustomAttenuation) {
  27063. sound.updateDistanceFromListener();
  27064. }
  27065. }
  27066. for (i = 0; i < this.soundTracks.length; i++) {
  27067. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27068. sound = this.soundTracks[i].soundCollection[j];
  27069. if (sound.useCustomAttenuation) {
  27070. sound.updateDistanceFromListener();
  27071. }
  27072. }
  27073. }
  27074. }
  27075. };
  27076. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27077. // Audio
  27078. /**
  27079. * Gets or sets if audio support is enabled
  27080. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27081. */
  27082. get: function () {
  27083. return this._audioEnabled;
  27084. },
  27085. set: function (value) {
  27086. this._audioEnabled = value;
  27087. if (BABYLON.AudioEngine) {
  27088. if (this._audioEnabled) {
  27089. this._enableAudio();
  27090. }
  27091. else {
  27092. this._disableAudio();
  27093. }
  27094. }
  27095. },
  27096. enumerable: true,
  27097. configurable: true
  27098. });
  27099. Scene.prototype._disableAudio = function () {
  27100. var i;
  27101. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27102. this.mainSoundTrack.soundCollection[i].pause();
  27103. }
  27104. for (i = 0; i < this.soundTracks.length; i++) {
  27105. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27106. this.soundTracks[i].soundCollection[j].pause();
  27107. }
  27108. }
  27109. };
  27110. Scene.prototype._enableAudio = function () {
  27111. var i;
  27112. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27113. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27114. this.mainSoundTrack.soundCollection[i].play();
  27115. }
  27116. }
  27117. for (i = 0; i < this.soundTracks.length; i++) {
  27118. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27119. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27120. this.soundTracks[i].soundCollection[j].play();
  27121. }
  27122. }
  27123. }
  27124. };
  27125. Object.defineProperty(Scene.prototype, "headphone", {
  27126. /**
  27127. * Gets or sets if audio will be output to headphones
  27128. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27129. */
  27130. get: function () {
  27131. return this._headphone;
  27132. },
  27133. set: function (value) {
  27134. this._headphone = value;
  27135. if (BABYLON.AudioEngine) {
  27136. if (this._headphone) {
  27137. this._switchAudioModeForHeadphones();
  27138. }
  27139. else {
  27140. this._switchAudioModeForNormalSpeakers();
  27141. }
  27142. }
  27143. },
  27144. enumerable: true,
  27145. configurable: true
  27146. });
  27147. Scene.prototype._switchAudioModeForHeadphones = function () {
  27148. this.mainSoundTrack.switchPanningModelToHRTF();
  27149. for (var i = 0; i < this.soundTracks.length; i++) {
  27150. this.soundTracks[i].switchPanningModelToHRTF();
  27151. }
  27152. };
  27153. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27154. this.mainSoundTrack.switchPanningModelToEqualPower();
  27155. for (var i = 0; i < this.soundTracks.length; i++) {
  27156. this.soundTracks[i].switchPanningModelToEqualPower();
  27157. }
  27158. };
  27159. /**
  27160. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27161. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27162. * @returns the created depth renderer
  27163. */
  27164. Scene.prototype.enableDepthRenderer = function (camera) {
  27165. camera = camera || this.activeCamera;
  27166. if (!camera) {
  27167. throw "No camera available to enable depth renderer";
  27168. }
  27169. if (!this._depthRenderer[camera.id]) {
  27170. var textureType = 0;
  27171. if (this._engine.getCaps().textureHalfFloatRender) {
  27172. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27173. }
  27174. else if (this._engine.getCaps().textureFloatRender) {
  27175. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27176. }
  27177. else {
  27178. throw "Depth renderer does not support int texture type";
  27179. }
  27180. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27181. }
  27182. return this._depthRenderer[camera.id];
  27183. };
  27184. /**
  27185. * Disables a depth renderer for a given camera
  27186. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27187. */
  27188. Scene.prototype.disableDepthRenderer = function (camera) {
  27189. camera = camera || this.activeCamera;
  27190. if (!camera || !this._depthRenderer[camera.id]) {
  27191. return;
  27192. }
  27193. this._depthRenderer[camera.id].dispose();
  27194. delete this._depthRenderer[camera.id];
  27195. };
  27196. /**
  27197. * Enables a GeometryBufferRender and associates it with the scene
  27198. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27199. * @returns the GeometryBufferRenderer
  27200. */
  27201. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27202. if (ratio === void 0) { ratio = 1; }
  27203. if (this._geometryBufferRenderer) {
  27204. return this._geometryBufferRenderer;
  27205. }
  27206. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27207. if (!this._geometryBufferRenderer.isSupported) {
  27208. this._geometryBufferRenderer = null;
  27209. }
  27210. return this._geometryBufferRenderer;
  27211. };
  27212. /**
  27213. * Disables the GeometryBufferRender associated with the scene
  27214. */
  27215. Scene.prototype.disableGeometryBufferRenderer = function () {
  27216. if (!this._geometryBufferRenderer) {
  27217. return;
  27218. }
  27219. this._geometryBufferRenderer.dispose();
  27220. this._geometryBufferRenderer = null;
  27221. };
  27222. /**
  27223. * Freeze all materials
  27224. * A frozen material will not be updatable but should be faster to render
  27225. */
  27226. Scene.prototype.freezeMaterials = function () {
  27227. for (var i = 0; i < this.materials.length; i++) {
  27228. this.materials[i].freeze();
  27229. }
  27230. };
  27231. /**
  27232. * Unfreeze all materials
  27233. * A frozen material will not be updatable but should be faster to render
  27234. */
  27235. Scene.prototype.unfreezeMaterials = function () {
  27236. for (var i = 0; i < this.materials.length; i++) {
  27237. this.materials[i].unfreeze();
  27238. }
  27239. };
  27240. /**
  27241. * Releases all held ressources
  27242. */
  27243. Scene.prototype.dispose = function () {
  27244. this.beforeRender = null;
  27245. this.afterRender = null;
  27246. this.skeletons = [];
  27247. this.morphTargetManagers = [];
  27248. this.importedMeshesFiles = new Array();
  27249. this.stopAllAnimations();
  27250. this.resetCachedMaterial();
  27251. for (var key in this._depthRenderer) {
  27252. this._depthRenderer[key].dispose();
  27253. }
  27254. if (this._gamepadManager) {
  27255. this._gamepadManager.dispose();
  27256. this._gamepadManager = null;
  27257. }
  27258. // Smart arrays
  27259. if (this.activeCamera) {
  27260. this.activeCamera._activeMeshes.dispose();
  27261. this.activeCamera = null;
  27262. }
  27263. this._activeMeshes.dispose();
  27264. this._renderingManager.dispose();
  27265. this._processedMaterials.dispose();
  27266. this._activeParticleSystems.dispose();
  27267. this._activeSkeletons.dispose();
  27268. this._softwareSkinnedMeshes.dispose();
  27269. this._renderTargets.dispose();
  27270. this._registeredForLateAnimationBindings.dispose();
  27271. if (this._boundingBoxRenderer) {
  27272. this._boundingBoxRenderer.dispose();
  27273. }
  27274. this._meshesForIntersections.dispose();
  27275. this._toBeDisposed.dispose();
  27276. // Abort active requests
  27277. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27278. var request = _a[_i];
  27279. request.abort();
  27280. }
  27281. // Debug layer
  27282. if (this._debugLayer) {
  27283. this._debugLayer.hide();
  27284. }
  27285. // Events
  27286. this.onDisposeObservable.notifyObservers(this);
  27287. this.onDisposeObservable.clear();
  27288. this.onBeforeRenderObservable.clear();
  27289. this.onAfterRenderObservable.clear();
  27290. this.onBeforeRenderTargetsRenderObservable.clear();
  27291. this.onAfterRenderTargetsRenderObservable.clear();
  27292. this.onAfterStepObservable.clear();
  27293. this.onBeforeStepObservable.clear();
  27294. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27295. this.onAfterActiveMeshesEvaluationObservable.clear();
  27296. this.onBeforeParticlesRenderingObservable.clear();
  27297. this.onAfterParticlesRenderingObservable.clear();
  27298. this.onBeforeSpritesRenderingObservable.clear();
  27299. this.onAfterSpritesRenderingObservable.clear();
  27300. this.onBeforeDrawPhaseObservable.clear();
  27301. this.onAfterDrawPhaseObservable.clear();
  27302. this.onBeforePhysicsObservable.clear();
  27303. this.onAfterPhysicsObservable.clear();
  27304. this.onBeforeAnimationsObservable.clear();
  27305. this.onAfterAnimationsObservable.clear();
  27306. this.onDataLoadedObservable.clear();
  27307. this.detachControl();
  27308. // Release sounds & sounds tracks
  27309. if (BABYLON.AudioEngine) {
  27310. this.disposeSounds();
  27311. }
  27312. // VR Helper
  27313. if (this.VRHelper) {
  27314. this.VRHelper.dispose();
  27315. }
  27316. // Detach cameras
  27317. var canvas = this._engine.getRenderingCanvas();
  27318. if (canvas) {
  27319. var index;
  27320. for (index = 0; index < this.cameras.length; index++) {
  27321. this.cameras[index].detachControl(canvas);
  27322. }
  27323. }
  27324. // Release animation groups
  27325. while (this.animationGroups.length) {
  27326. this.animationGroups[0].dispose();
  27327. }
  27328. // Release lights
  27329. while (this.lights.length) {
  27330. this.lights[0].dispose();
  27331. }
  27332. // Release meshes
  27333. while (this.meshes.length) {
  27334. this.meshes[0].dispose(true);
  27335. }
  27336. while (this.transformNodes.length) {
  27337. this.removeTransformNode(this.transformNodes[0]);
  27338. }
  27339. // Release cameras
  27340. while (this.cameras.length) {
  27341. this.cameras[0].dispose();
  27342. }
  27343. // Release materials
  27344. if (this.defaultMaterial) {
  27345. this.defaultMaterial.dispose();
  27346. }
  27347. while (this.multiMaterials.length) {
  27348. this.multiMaterials[0].dispose();
  27349. }
  27350. while (this.materials.length) {
  27351. this.materials[0].dispose();
  27352. }
  27353. // Release particles
  27354. while (this.particleSystems.length) {
  27355. this.particleSystems[0].dispose();
  27356. }
  27357. // Release sprites
  27358. while (this.spriteManagers.length) {
  27359. this.spriteManagers[0].dispose();
  27360. }
  27361. // Release postProcesses
  27362. while (this.postProcesses.length) {
  27363. this.postProcesses[0].dispose();
  27364. }
  27365. // Release layers
  27366. while (this.layers.length) {
  27367. this.layers[0].dispose();
  27368. }
  27369. while (this.effectLayers.length) {
  27370. this.effectLayers[0].dispose();
  27371. }
  27372. // Release textures
  27373. while (this.textures.length) {
  27374. this.textures[0].dispose();
  27375. }
  27376. // Release UBO
  27377. this._sceneUbo.dispose();
  27378. if (this._alternateSceneUbo) {
  27379. this._alternateSceneUbo.dispose();
  27380. }
  27381. // Post-processes
  27382. this.postProcessManager.dispose();
  27383. if (this._postProcessRenderPipelineManager) {
  27384. this._postProcessRenderPipelineManager.dispose();
  27385. }
  27386. // Physics
  27387. if (this._physicsEngine) {
  27388. this.disablePhysicsEngine();
  27389. }
  27390. // Remove from engine
  27391. index = this._engine.scenes.indexOf(this);
  27392. if (index > -1) {
  27393. this._engine.scenes.splice(index, 1);
  27394. }
  27395. this._engine.wipeCaches(true);
  27396. this._isDisposed = true;
  27397. };
  27398. Object.defineProperty(Scene.prototype, "isDisposed", {
  27399. /**
  27400. * Gets if the scene is already disposed
  27401. */
  27402. get: function () {
  27403. return this._isDisposed;
  27404. },
  27405. enumerable: true,
  27406. configurable: true
  27407. });
  27408. /**
  27409. * Releases sounds & soundtracks
  27410. */
  27411. Scene.prototype.disposeSounds = function () {
  27412. if (!this._mainSoundTrack) {
  27413. return;
  27414. }
  27415. this.mainSoundTrack.dispose();
  27416. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27417. this.soundTracks[scIndex].dispose();
  27418. }
  27419. };
  27420. // Octrees
  27421. /**
  27422. * Get the world extend vectors with an optional filter
  27423. *
  27424. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27425. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27426. */
  27427. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27428. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27429. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27430. filterPredicate = filterPredicate || (function () { return true; });
  27431. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27432. mesh.computeWorldMatrix(true);
  27433. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27434. return;
  27435. }
  27436. var boundingInfo = mesh.getBoundingInfo();
  27437. var minBox = boundingInfo.boundingBox.minimumWorld;
  27438. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27439. BABYLON.Tools.CheckExtends(minBox, min, max);
  27440. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27441. });
  27442. return {
  27443. min: min,
  27444. max: max
  27445. };
  27446. };
  27447. /**
  27448. * Creates or updates the octree used to boost selection (picking)
  27449. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27450. * @param maxCapacity defines the maximum capacity per leaf
  27451. * @param maxDepth defines the maximum depth of the octree
  27452. * @returns an octree of AbstractMesh
  27453. */
  27454. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27455. if (maxCapacity === void 0) { maxCapacity = 64; }
  27456. if (maxDepth === void 0) { maxDepth = 2; }
  27457. if (!this._selectionOctree) {
  27458. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27459. }
  27460. var worldExtends = this.getWorldExtends();
  27461. // Update octree
  27462. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27463. return this._selectionOctree;
  27464. };
  27465. // Picking
  27466. /**
  27467. * Creates a ray that can be used to pick in the scene
  27468. * @param x defines the x coordinate of the origin (on-screen)
  27469. * @param y defines the y coordinate of the origin (on-screen)
  27470. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27471. * @param camera defines the camera to use for the picking
  27472. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27473. * @returns a Ray
  27474. */
  27475. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27476. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27477. var result = BABYLON.Ray.Zero();
  27478. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27479. return result;
  27480. };
  27481. /**
  27482. * Creates a ray that can be used to pick in the scene
  27483. * @param x defines the x coordinate of the origin (on-screen)
  27484. * @param y defines the y coordinate of the origin (on-screen)
  27485. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27486. * @param result defines the ray where to store the picking ray
  27487. * @param camera defines the camera to use for the picking
  27488. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27489. * @returns the current scene
  27490. */
  27491. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27492. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27493. var engine = this._engine;
  27494. if (!camera) {
  27495. if (!this.activeCamera)
  27496. throw new Error("Active camera not set");
  27497. camera = this.activeCamera;
  27498. }
  27499. var cameraViewport = camera.viewport;
  27500. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27501. // Moving coordinates to local viewport world
  27502. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27503. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27504. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27505. return this;
  27506. };
  27507. /**
  27508. * Creates a ray that can be used to pick in the scene
  27509. * @param x defines the x coordinate of the origin (on-screen)
  27510. * @param y defines the y coordinate of the origin (on-screen)
  27511. * @param camera defines the camera to use for the picking
  27512. * @returns a Ray
  27513. */
  27514. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27515. var result = BABYLON.Ray.Zero();
  27516. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27517. return result;
  27518. };
  27519. /**
  27520. * Creates a ray that can be used to pick in the scene
  27521. * @param x defines the x coordinate of the origin (on-screen)
  27522. * @param y defines the y coordinate of the origin (on-screen)
  27523. * @param result defines the ray where to store the picking ray
  27524. * @param camera defines the camera to use for the picking
  27525. * @returns the current scene
  27526. */
  27527. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27528. if (!BABYLON.PickingInfo) {
  27529. return this;
  27530. }
  27531. var engine = this._engine;
  27532. if (!camera) {
  27533. if (!this.activeCamera)
  27534. throw new Error("Active camera not set");
  27535. camera = this.activeCamera;
  27536. }
  27537. var cameraViewport = camera.viewport;
  27538. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27539. var identity = BABYLON.Matrix.Identity();
  27540. // Moving coordinates to local viewport world
  27541. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27542. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27543. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27544. return this;
  27545. };
  27546. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27547. if (!BABYLON.PickingInfo) {
  27548. return null;
  27549. }
  27550. var pickingInfo = null;
  27551. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27552. var mesh = this.meshes[meshIndex];
  27553. if (predicate) {
  27554. if (!predicate(mesh)) {
  27555. continue;
  27556. }
  27557. }
  27558. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27559. continue;
  27560. }
  27561. var world = mesh.getWorldMatrix();
  27562. var ray = rayFunction(world);
  27563. var result = mesh.intersects(ray, fastCheck);
  27564. if (!result || !result.hit)
  27565. continue;
  27566. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27567. continue;
  27568. pickingInfo = result;
  27569. if (fastCheck) {
  27570. break;
  27571. }
  27572. }
  27573. return pickingInfo || new BABYLON.PickingInfo();
  27574. };
  27575. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27576. if (!BABYLON.PickingInfo) {
  27577. return null;
  27578. }
  27579. var pickingInfos = new Array();
  27580. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27581. var mesh = this.meshes[meshIndex];
  27582. if (predicate) {
  27583. if (!predicate(mesh)) {
  27584. continue;
  27585. }
  27586. }
  27587. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27588. continue;
  27589. }
  27590. var world = mesh.getWorldMatrix();
  27591. var ray = rayFunction(world);
  27592. var result = mesh.intersects(ray, false);
  27593. if (!result || !result.hit)
  27594. continue;
  27595. pickingInfos.push(result);
  27596. }
  27597. return pickingInfos;
  27598. };
  27599. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27600. if (!BABYLON.PickingInfo) {
  27601. return null;
  27602. }
  27603. var pickingInfo = null;
  27604. if (!camera) {
  27605. if (!this.activeCamera) {
  27606. return null;
  27607. }
  27608. camera = this.activeCamera;
  27609. }
  27610. if (this.spriteManagers.length > 0) {
  27611. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  27612. var spriteManager = this.spriteManagers[spriteIndex];
  27613. if (!spriteManager.isPickable) {
  27614. continue;
  27615. }
  27616. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  27617. if (!result || !result.hit)
  27618. continue;
  27619. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27620. continue;
  27621. pickingInfo = result;
  27622. if (fastCheck) {
  27623. break;
  27624. }
  27625. }
  27626. }
  27627. return pickingInfo || new BABYLON.PickingInfo();
  27628. };
  27629. /** Launch a ray to try to pick a mesh in the scene
  27630. * @param x position on screen
  27631. * @param y position on screen
  27632. * @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
  27633. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27634. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27635. * @returns a PickingInfo
  27636. */
  27637. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  27638. var _this = this;
  27639. if (!BABYLON.PickingInfo) {
  27640. return null;
  27641. }
  27642. return this._internalPick(function (world) {
  27643. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  27644. return _this._tempPickingRay;
  27645. }, predicate, fastCheck);
  27646. };
  27647. /** Launch a ray to try to pick a sprite in the scene
  27648. * @param x position on screen
  27649. * @param y position on screen
  27650. * @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
  27651. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27652. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27653. * @returns a PickingInfo
  27654. */
  27655. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  27656. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  27657. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  27658. };
  27659. /** Use the given ray to pick a mesh in the scene
  27660. * @param ray The ray to use to pick meshes
  27661. * @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
  27662. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  27663. * @returns a PickingInfo
  27664. */
  27665. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  27666. var _this = this;
  27667. return this._internalPick(function (world) {
  27668. if (!_this._pickWithRayInverseMatrix) {
  27669. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27670. }
  27671. world.invertToRef(_this._pickWithRayInverseMatrix);
  27672. if (!_this._cachedRayForTransform) {
  27673. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27674. }
  27675. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27676. return _this._cachedRayForTransform;
  27677. }, predicate, fastCheck);
  27678. };
  27679. /**
  27680. * Launch a ray to try to pick a mesh in the scene
  27681. * @param x X position on screen
  27682. * @param y Y position on screen
  27683. * @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
  27684. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27685. * @returns an array of PickingInfo
  27686. */
  27687. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  27688. var _this = this;
  27689. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  27690. };
  27691. /**
  27692. * Launch a ray to try to pick a mesh in the scene
  27693. * @param ray Ray to use
  27694. * @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
  27695. * @returns an array of PickingInfo
  27696. */
  27697. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  27698. var _this = this;
  27699. return this._internalMultiPick(function (world) {
  27700. if (!_this._pickWithRayInverseMatrix) {
  27701. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27702. }
  27703. world.invertToRef(_this._pickWithRayInverseMatrix);
  27704. if (!_this._cachedRayForTransform) {
  27705. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27706. }
  27707. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27708. return _this._cachedRayForTransform;
  27709. }, predicate);
  27710. };
  27711. /**
  27712. * Force the value of meshUnderPointer
  27713. * @param mesh defines the mesh to use
  27714. */
  27715. Scene.prototype.setPointerOverMesh = function (mesh) {
  27716. if (this._pointerOverMesh === mesh) {
  27717. return;
  27718. }
  27719. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27720. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27721. }
  27722. this._pointerOverMesh = mesh;
  27723. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27724. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27725. }
  27726. };
  27727. /**
  27728. * Gets the mesh under the pointer
  27729. * @returns a Mesh or null if no mesh is under the pointer
  27730. */
  27731. Scene.prototype.getPointerOverMesh = function () {
  27732. return this._pointerOverMesh;
  27733. };
  27734. /**
  27735. * Force the sprite under the pointer
  27736. * @param sprite defines the sprite to use
  27737. */
  27738. Scene.prototype.setPointerOverSprite = function (sprite) {
  27739. if (this._pointerOverSprite === sprite) {
  27740. return;
  27741. }
  27742. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27743. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27744. }
  27745. this._pointerOverSprite = sprite;
  27746. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27747. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27748. }
  27749. };
  27750. /**
  27751. * Gets the sprite under the pointer
  27752. * @returns a Sprite or null if no sprite is under the pointer
  27753. */
  27754. Scene.prototype.getPointerOverSprite = function () {
  27755. return this._pointerOverSprite;
  27756. };
  27757. // Physics
  27758. /**
  27759. * Gets the current physics engine
  27760. * @returns a PhysicsEngine or null if none attached
  27761. */
  27762. Scene.prototype.getPhysicsEngine = function () {
  27763. return this._physicsEngine;
  27764. };
  27765. /**
  27766. * Enables physics to the current scene
  27767. * @param gravity defines the scene's gravity for the physics engine
  27768. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  27769. * @return a boolean indicating if the physics engine was initialized
  27770. */
  27771. Scene.prototype.enablePhysics = function (gravity, plugin) {
  27772. if (gravity === void 0) { gravity = null; }
  27773. if (this._physicsEngine) {
  27774. return true;
  27775. }
  27776. try {
  27777. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  27778. return true;
  27779. }
  27780. catch (e) {
  27781. BABYLON.Tools.Error(e.message);
  27782. return false;
  27783. }
  27784. };
  27785. /**
  27786. * Disables and disposes the physics engine associated with the scene
  27787. */
  27788. Scene.prototype.disablePhysicsEngine = function () {
  27789. if (!this._physicsEngine) {
  27790. return;
  27791. }
  27792. this._physicsEngine.dispose();
  27793. this._physicsEngine = null;
  27794. };
  27795. /**
  27796. * Gets a boolean indicating if there is an active physics engine
  27797. * @returns a boolean indicating if there is an active physics engine
  27798. */
  27799. Scene.prototype.isPhysicsEnabled = function () {
  27800. return this._physicsEngine !== undefined;
  27801. };
  27802. /**
  27803. * Deletes a physics compound impostor
  27804. * @param compound defines the compound to delete
  27805. */
  27806. Scene.prototype.deleteCompoundImpostor = function (compound) {
  27807. var mesh = compound.parts[0].mesh;
  27808. if (mesh.physicsImpostor) {
  27809. mesh.physicsImpostor.dispose();
  27810. mesh.physicsImpostor = null;
  27811. }
  27812. };
  27813. // Misc.
  27814. /** @ignore */
  27815. Scene.prototype._rebuildGeometries = function () {
  27816. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  27817. var geometry = _a[_i];
  27818. geometry._rebuild();
  27819. }
  27820. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  27821. var mesh = _c[_b];
  27822. mesh._rebuild();
  27823. }
  27824. if (this.postProcessManager) {
  27825. this.postProcessManager._rebuild();
  27826. }
  27827. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  27828. var layer = _e[_d];
  27829. layer._rebuild();
  27830. }
  27831. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  27832. var effectLayer = _g[_f];
  27833. effectLayer._rebuild();
  27834. }
  27835. if (this._boundingBoxRenderer) {
  27836. this._boundingBoxRenderer._rebuild();
  27837. }
  27838. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  27839. var system = _j[_h];
  27840. system.rebuild();
  27841. }
  27842. if (this._postProcessRenderPipelineManager) {
  27843. this._postProcessRenderPipelineManager._rebuild();
  27844. }
  27845. };
  27846. /** @ignore */
  27847. Scene.prototype._rebuildTextures = function () {
  27848. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27849. var texture = _a[_i];
  27850. texture._rebuild();
  27851. }
  27852. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27853. };
  27854. /**
  27855. * Creates a default light for the scene.
  27856. * @param replace Whether to replace the existing lights in the scene.
  27857. */
  27858. Scene.prototype.createDefaultLight = function (replace) {
  27859. if (replace === void 0) { replace = false; }
  27860. // Dispose existing light in replace mode.
  27861. if (replace) {
  27862. if (this.lights) {
  27863. for (var i = 0; i < this.lights.length; i++) {
  27864. this.lights[i].dispose();
  27865. }
  27866. }
  27867. }
  27868. // Light
  27869. if (this.lights.length === 0) {
  27870. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  27871. }
  27872. };
  27873. /**
  27874. * Creates a default camera for the scene.
  27875. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  27876. * @param replace Whether to replace the existing active camera in the scene.
  27877. * @param attachCameraControls Whether to attach camera controls to the canvas.
  27878. */
  27879. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  27880. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27881. if (replace === void 0) { replace = false; }
  27882. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27883. // Dispose existing camera in replace mode.
  27884. if (replace) {
  27885. if (this.activeCamera) {
  27886. this.activeCamera.dispose();
  27887. this.activeCamera = null;
  27888. }
  27889. }
  27890. // Camera
  27891. if (!this.activeCamera) {
  27892. var worldExtends = this.getWorldExtends();
  27893. var worldSize = worldExtends.max.subtract(worldExtends.min);
  27894. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  27895. var camera;
  27896. var radius = worldSize.length() * 1.5;
  27897. // empty scene scenario!
  27898. if (!isFinite(radius)) {
  27899. radius = 1;
  27900. worldCenter.copyFromFloats(0, 0, 0);
  27901. }
  27902. if (createArcRotateCamera) {
  27903. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  27904. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  27905. arcRotateCamera.wheelPrecision = 100 / radius;
  27906. camera = arcRotateCamera;
  27907. }
  27908. else {
  27909. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  27910. freeCamera.setTarget(worldCenter);
  27911. camera = freeCamera;
  27912. }
  27913. camera.minZ = radius * 0.01;
  27914. camera.maxZ = radius * 1000;
  27915. camera.speed = radius * 0.2;
  27916. this.activeCamera = camera;
  27917. var canvas = this.getEngine().getRenderingCanvas();
  27918. if (attachCameraControls && canvas) {
  27919. camera.attachControl(canvas);
  27920. }
  27921. }
  27922. };
  27923. /**
  27924. * Creates a default camera and a default light
  27925. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  27926. * @param replace defines if the camera and/or light will replace the existing ones
  27927. * @param attachCameraControls defines if attachControl will be called on the new camera
  27928. */
  27929. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  27930. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27931. if (replace === void 0) { replace = false; }
  27932. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27933. this.createDefaultLight(replace);
  27934. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  27935. };
  27936. /**
  27937. * Creates a new sky box
  27938. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  27939. * @param environmentTexture defines the texture to use as environment texture
  27940. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  27941. * @param scale defines the overall scale of the skybox
  27942. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  27943. * @returns a new mesh holding the sky box
  27944. */
  27945. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  27946. if (pbr === void 0) { pbr = false; }
  27947. if (scale === void 0) { scale = 1000; }
  27948. if (blur === void 0) { blur = 0; }
  27949. if (environmentTexture) {
  27950. this.environmentTexture = environmentTexture;
  27951. }
  27952. if (!this.environmentTexture) {
  27953. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  27954. return null;
  27955. }
  27956. // Skybox
  27957. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  27958. if (pbr) {
  27959. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  27960. hdrSkyboxMaterial.backFaceCulling = false;
  27961. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  27962. if (hdrSkyboxMaterial.reflectionTexture) {
  27963. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  27964. }
  27965. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  27966. hdrSkyboxMaterial.disableLighting = true;
  27967. hdrSkyboxMaterial.twoSidedLighting = true;
  27968. hdrSkybox.infiniteDistance = true;
  27969. hdrSkybox.material = hdrSkyboxMaterial;
  27970. }
  27971. else {
  27972. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  27973. skyboxMaterial.backFaceCulling = false;
  27974. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  27975. if (skyboxMaterial.reflectionTexture) {
  27976. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  27977. }
  27978. skyboxMaterial.disableLighting = true;
  27979. hdrSkybox.infiniteDistance = true;
  27980. hdrSkybox.material = skyboxMaterial;
  27981. }
  27982. return hdrSkybox;
  27983. };
  27984. /**
  27985. * Creates a new environment
  27986. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  27987. * @param options defines the options you can use to configure the environment
  27988. * @returns the new EnvironmentHelper
  27989. */
  27990. Scene.prototype.createDefaultEnvironment = function (options) {
  27991. if (BABYLON.EnvironmentHelper) {
  27992. return new BABYLON.EnvironmentHelper(options, this);
  27993. }
  27994. return null;
  27995. };
  27996. /**
  27997. * Creates a new VREXperienceHelper
  27998. * @see http://doc.babylonjs.com/how_to/webvr_helper
  27999. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28000. * @returns a new VREXperienceHelper
  28001. */
  28002. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28003. if (webVROptions === void 0) { webVROptions = {}; }
  28004. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28005. };
  28006. // Tags
  28007. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28008. if (tagsQuery === undefined) {
  28009. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28010. return list;
  28011. }
  28012. var listByTags = [];
  28013. forEach = forEach || (function (item) { return; });
  28014. for (var i in list) {
  28015. var item = list[i];
  28016. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28017. listByTags.push(item);
  28018. forEach(item);
  28019. }
  28020. }
  28021. return listByTags;
  28022. };
  28023. /**
  28024. * Get a list of meshes by tags
  28025. * @param tagsQuery defines the tags query to use
  28026. * @param forEach defines a predicate used to filter results
  28027. * @returns an array of Mesh
  28028. */
  28029. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28030. return this._getByTags(this.meshes, tagsQuery, forEach);
  28031. };
  28032. /**
  28033. * Get a list of cameras by tags
  28034. * @param tagsQuery defines the tags query to use
  28035. * @param forEach defines a predicate used to filter results
  28036. * @returns an array of Camera
  28037. */
  28038. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28039. return this._getByTags(this.cameras, tagsQuery, forEach);
  28040. };
  28041. /**
  28042. * Get a list of lights by tags
  28043. * @param tagsQuery defines the tags query to use
  28044. * @param forEach defines a predicate used to filter results
  28045. * @returns an array of Light
  28046. */
  28047. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28048. return this._getByTags(this.lights, tagsQuery, forEach);
  28049. };
  28050. /**
  28051. * Get a list of materials by tags
  28052. * @param tagsQuery defines the tags query to use
  28053. * @param forEach defines a predicate used to filter results
  28054. * @returns an array of Material
  28055. */
  28056. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28057. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28058. };
  28059. /**
  28060. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28061. * This allowed control for front to back rendering or reversly depending of the special needs.
  28062. *
  28063. * @param renderingGroupId The rendering group id corresponding to its index
  28064. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28065. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28066. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28067. */
  28068. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28069. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28070. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28071. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28072. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28073. };
  28074. /**
  28075. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28076. *
  28077. * @param renderingGroupId The rendering group id corresponding to its index
  28078. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28079. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28080. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28081. */
  28082. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28083. if (depth === void 0) { depth = true; }
  28084. if (stencil === void 0) { stencil = true; }
  28085. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28086. };
  28087. /**
  28088. * Will flag all materials as dirty to trigger new shader compilation
  28089. * @param flag defines the flag used to specify which material part must be marked as dirty
  28090. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28091. */
  28092. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28093. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28094. var material = _a[_i];
  28095. if (predicate && !predicate(material)) {
  28096. continue;
  28097. }
  28098. material.markAsDirty(flag);
  28099. }
  28100. };
  28101. /** @ignore */
  28102. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28103. var _this = this;
  28104. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28105. this._activeRequests.push(request);
  28106. request.onCompleteObservable.add(function (request) {
  28107. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28108. });
  28109. return request;
  28110. };
  28111. /** @ignore */
  28112. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28113. var _this = this;
  28114. return new Promise(function (resolve, reject) {
  28115. _this._loadFile(url, function (data) {
  28116. resolve(data);
  28117. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28118. reject(exception);
  28119. });
  28120. });
  28121. };
  28122. // Statics
  28123. Scene._FOGMODE_NONE = 0;
  28124. Scene._FOGMODE_EXP = 1;
  28125. Scene._FOGMODE_EXP2 = 2;
  28126. Scene._FOGMODE_LINEAR = 3;
  28127. Scene._uniqueIdCounter = 0;
  28128. /**
  28129. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28130. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28131. */
  28132. Scene.MinDeltaTime = 1.0;
  28133. /**
  28134. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28135. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28136. */
  28137. Scene.MaxDeltaTime = 1000.0;
  28138. /** The distance in pixel that you have to move to prevent some events */
  28139. Scene.DragMovementThreshold = 10; // in pixels
  28140. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28141. Scene.LongPressDelay = 500; // in milliseconds
  28142. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28143. Scene.DoubleClickDelay = 300; // in milliseconds
  28144. /** If you need to check double click without raising a single click at first click, enable this flag */
  28145. Scene.ExclusiveDoubleClickMode = false;
  28146. return Scene;
  28147. }());
  28148. BABYLON.Scene = Scene;
  28149. })(BABYLON || (BABYLON = {}));
  28150. //# sourceMappingURL=babylon.scene.js.map
  28151. "use strict";
  28152. var BABYLON;
  28153. (function (BABYLON) {
  28154. /**
  28155. * Set of assets to keep when moving a scene into an asset container.
  28156. */
  28157. var KeepAssets = /** @class */ (function () {
  28158. function KeepAssets() {
  28159. /**
  28160. * Cameras to keep.
  28161. */
  28162. this.cameras = new Array();
  28163. /**
  28164. * Lights to keep.
  28165. */
  28166. this.lights = new Array();
  28167. /**
  28168. * Meshes to keep.
  28169. */
  28170. this.meshes = new Array();
  28171. /**
  28172. * Skeletons to keep.
  28173. */
  28174. this.skeletons = new Array();
  28175. /**
  28176. * ParticleSystems to keep.
  28177. */
  28178. this.particleSystems = new Array();
  28179. /**
  28180. * Animations to keep.
  28181. */
  28182. this.animations = new Array();
  28183. /**
  28184. * AnimationGroups to keep.
  28185. */
  28186. this.animationGroups = new Array();
  28187. /**
  28188. * MultiMaterials to keep.
  28189. */
  28190. this.multiMaterials = new Array();
  28191. /**
  28192. * Materials to keep.
  28193. */
  28194. this.materials = new Array();
  28195. /**
  28196. * MorphTargetManagers to keep.
  28197. */
  28198. this.morphTargetManagers = new Array();
  28199. /**
  28200. * Geometries to keep.
  28201. */
  28202. this.geometries = new Array();
  28203. /**
  28204. * TransformNodes to keep.
  28205. */
  28206. this.transformNodes = new Array();
  28207. /**
  28208. * LensFlareSystems to keep.
  28209. */
  28210. this.lensFlareSystems = new Array();
  28211. /**
  28212. * ShadowGenerators to keep.
  28213. */
  28214. this.shadowGenerators = new Array();
  28215. /**
  28216. * ActionManagers to keep.
  28217. */
  28218. this.actionManagers = new Array();
  28219. /**
  28220. * Sounds to keep.
  28221. */
  28222. this.sounds = new Array();
  28223. /**
  28224. * Textures to keep.
  28225. */
  28226. this.textures = new Array();
  28227. /**
  28228. * Effect layers to keep.
  28229. */
  28230. this.effectLayers = new Array();
  28231. }
  28232. return KeepAssets;
  28233. }());
  28234. BABYLON.KeepAssets = KeepAssets;
  28235. /**
  28236. * Container with a set of assets that can be added or removed from a scene.
  28237. */
  28238. var AssetContainer = /** @class */ (function () {
  28239. /**
  28240. * Instantiates an AssetContainer.
  28241. * @param scene The scene the AssetContainer belongs to.
  28242. */
  28243. function AssetContainer(scene) {
  28244. // Objects
  28245. /**
  28246. * Cameras populated in the container.
  28247. */
  28248. this.cameras = new Array();
  28249. /**
  28250. * Lights populated in the container.
  28251. */
  28252. this.lights = new Array();
  28253. /**
  28254. * Meshes populated in the container.
  28255. */
  28256. this.meshes = new Array();
  28257. /**
  28258. * Skeletons populated in the container.
  28259. */
  28260. this.skeletons = new Array();
  28261. /**
  28262. * ParticleSystems populated in the container.
  28263. */
  28264. this.particleSystems = new Array();
  28265. /**
  28266. * Animations populated in the container.
  28267. */
  28268. this.animations = new Array();
  28269. /**
  28270. * AnimationGroups populated in the container.
  28271. */
  28272. this.animationGroups = new Array();
  28273. /**
  28274. * MultiMaterials populated in the container.
  28275. */
  28276. this.multiMaterials = new Array();
  28277. /**
  28278. * Materials populated in the container.
  28279. */
  28280. this.materials = new Array();
  28281. /**
  28282. * MorphTargetManagers populated in the container.
  28283. */
  28284. this.morphTargetManagers = new Array();
  28285. /**
  28286. * Geometries populated in the container.
  28287. */
  28288. this.geometries = new Array();
  28289. /**
  28290. * TransformNodes populated in the container.
  28291. */
  28292. this.transformNodes = new Array();
  28293. /**
  28294. * LensFlareSystems populated in the container.
  28295. */
  28296. this.lensFlareSystems = new Array();
  28297. /**
  28298. * ShadowGenerators populated in the container.
  28299. */
  28300. this.shadowGenerators = new Array();
  28301. /**
  28302. * ActionManagers populated in the container.
  28303. */
  28304. this.actionManagers = new Array();
  28305. /**
  28306. * Sounds populated in the container.
  28307. */
  28308. this.sounds = new Array();
  28309. /**
  28310. * Textures populated in the container.
  28311. */
  28312. this.textures = new Array();
  28313. /**
  28314. * Effect layers populated in the container.
  28315. */
  28316. this.effectLayers = new Array();
  28317. this.scene = scene;
  28318. }
  28319. /**
  28320. * Adds all the assets from the container to the scene.
  28321. */
  28322. AssetContainer.prototype.addAllToScene = function () {
  28323. var _this = this;
  28324. this.cameras.forEach(function (o) {
  28325. _this.scene.addCamera(o);
  28326. });
  28327. this.lights.forEach(function (o) {
  28328. _this.scene.addLight(o);
  28329. });
  28330. this.meshes.forEach(function (o) {
  28331. _this.scene.addMesh(o);
  28332. });
  28333. this.skeletons.forEach(function (o) {
  28334. _this.scene.addSkeleton(o);
  28335. });
  28336. this.particleSystems.forEach(function (o) {
  28337. _this.scene.addParticleSystem(o);
  28338. });
  28339. this.animations.forEach(function (o) {
  28340. _this.scene.addAnimation(o);
  28341. });
  28342. this.animationGroups.forEach(function (o) {
  28343. _this.scene.addAnimationGroup(o);
  28344. });
  28345. this.multiMaterials.forEach(function (o) {
  28346. _this.scene.addMultiMaterial(o);
  28347. });
  28348. this.materials.forEach(function (o) {
  28349. _this.scene.addMaterial(o);
  28350. });
  28351. this.morphTargetManagers.forEach(function (o) {
  28352. _this.scene.addMorphTargetManager(o);
  28353. });
  28354. this.geometries.forEach(function (o) {
  28355. _this.scene.addGeometry(o);
  28356. });
  28357. this.transformNodes.forEach(function (o) {
  28358. _this.scene.addTransformNode(o);
  28359. });
  28360. this.lensFlareSystems.forEach(function (o) {
  28361. _this.scene.addLensFlareSystem(o);
  28362. });
  28363. this.actionManagers.forEach(function (o) {
  28364. _this.scene.addActionManager(o);
  28365. });
  28366. this.sounds.forEach(function (o) {
  28367. o.play();
  28368. o.autoplay = true;
  28369. _this.scene.mainSoundTrack.AddSound(o);
  28370. });
  28371. this.textures.forEach(function (o) {
  28372. _this.scene.addTexture(o);
  28373. });
  28374. this.effectLayers.forEach(function (o) {
  28375. _this.scene.addEffectLayer(o);
  28376. });
  28377. };
  28378. /**
  28379. * Removes all the assets in the container from the scene
  28380. */
  28381. AssetContainer.prototype.removeAllFromScene = function () {
  28382. var _this = this;
  28383. this.cameras.forEach(function (o) {
  28384. _this.scene.removeCamera(o);
  28385. });
  28386. this.lights.forEach(function (o) {
  28387. _this.scene.removeLight(o);
  28388. });
  28389. this.meshes.forEach(function (o) {
  28390. _this.scene.removeMesh(o);
  28391. });
  28392. this.skeletons.forEach(function (o) {
  28393. _this.scene.removeSkeleton(o);
  28394. });
  28395. this.particleSystems.forEach(function (o) {
  28396. _this.scene.removeParticleSystem(o);
  28397. });
  28398. this.animations.forEach(function (o) {
  28399. _this.scene.removeAnimation(o);
  28400. });
  28401. this.animationGroups.forEach(function (o) {
  28402. _this.scene.removeAnimationGroup(o);
  28403. });
  28404. this.multiMaterials.forEach(function (o) {
  28405. _this.scene.removeMultiMaterial(o);
  28406. });
  28407. this.materials.forEach(function (o) {
  28408. _this.scene.removeMaterial(o);
  28409. });
  28410. this.morphTargetManagers.forEach(function (o) {
  28411. _this.scene.removeMorphTargetManager(o);
  28412. });
  28413. this.geometries.forEach(function (o) {
  28414. _this.scene.removeGeometry(o);
  28415. });
  28416. this.transformNodes.forEach(function (o) {
  28417. _this.scene.removeTransformNode(o);
  28418. });
  28419. this.lensFlareSystems.forEach(function (o) {
  28420. _this.scene.removeLensFlareSystem(o);
  28421. });
  28422. this.actionManagers.forEach(function (o) {
  28423. _this.scene.removeActionManager(o);
  28424. });
  28425. this.sounds.forEach(function (o) {
  28426. o.stop();
  28427. o.autoplay = false;
  28428. _this.scene.mainSoundTrack.RemoveSound(o);
  28429. });
  28430. this.textures.forEach(function (o) {
  28431. _this.scene.removeTexture(o);
  28432. });
  28433. this.effectLayers.forEach(function (o) {
  28434. _this.scene.removeEffectLayer(o);
  28435. });
  28436. };
  28437. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28438. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28439. var asset = sourceAssets_1[_i];
  28440. var move = true;
  28441. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28442. var keepAsset = keepAssets_1[_a];
  28443. if (asset === keepAsset) {
  28444. move = false;
  28445. break;
  28446. }
  28447. }
  28448. if (move) {
  28449. targetAssets.push(asset);
  28450. }
  28451. }
  28452. };
  28453. /**
  28454. * Removes all the assets contained in the scene and adds them to the container.
  28455. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28456. */
  28457. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28458. if (keepAssets === undefined) {
  28459. keepAssets = new KeepAssets();
  28460. }
  28461. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28462. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28463. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28464. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28465. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28466. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28467. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28468. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28469. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28470. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28471. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28472. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28473. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28474. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28475. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28476. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28477. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  28478. this.removeAllFromScene();
  28479. };
  28480. return AssetContainer;
  28481. }());
  28482. BABYLON.AssetContainer = AssetContainer;
  28483. })(BABYLON || (BABYLON = {}));
  28484. //# sourceMappingURL=babylon.assetContainer.js.map
  28485. "use strict";
  28486. var BABYLON;
  28487. (function (BABYLON) {
  28488. var Buffer = /** @class */ (function () {
  28489. /**
  28490. * Constructor
  28491. * @param engine the engine
  28492. * @param data the data to use for this buffer
  28493. * @param updatable whether the data is updatable
  28494. * @param stride the stride (optional)
  28495. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28496. * @param instanced whether the buffer is instanced (optional)
  28497. * @param useBytes set to true if the stride in in bytes (optional)
  28498. */
  28499. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28500. if (stride === void 0) { stride = 0; }
  28501. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28502. if (instanced === void 0) { instanced = false; }
  28503. if (useBytes === void 0) { useBytes = false; }
  28504. if (engine instanceof BABYLON.Mesh) {
  28505. this._engine = engine.getScene().getEngine();
  28506. }
  28507. else {
  28508. this._engine = engine;
  28509. }
  28510. this._updatable = updatable;
  28511. this._instanced = instanced;
  28512. this._data = data;
  28513. this.byteStride = useBytes ? stride : stride * 4;
  28514. if (!postponeInternalCreation) {
  28515. this.create();
  28516. }
  28517. }
  28518. /**
  28519. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28520. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28521. * @param offset defines offset in the buffer (0 by default)
  28522. * @param size defines the size in floats of attributes (position is 3 for instance)
  28523. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28524. * @param instanced defines if the vertex buffer contains indexed data
  28525. * @param useBytes defines if the offset and stride are in bytes
  28526. * @returns the new vertex buffer
  28527. */
  28528. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28529. if (useBytes === void 0) { useBytes = false; }
  28530. var byteOffset = useBytes ? offset : offset * 4;
  28531. var byteStride = stride ? (useBytes ? stride : stride * 4) : this.byteStride;
  28532. // a lot of these parameters are ignored as they are overriden by the buffer
  28533. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28534. };
  28535. // Properties
  28536. Buffer.prototype.isUpdatable = function () {
  28537. return this._updatable;
  28538. };
  28539. Buffer.prototype.getData = function () {
  28540. return this._data;
  28541. };
  28542. Buffer.prototype.getBuffer = function () {
  28543. return this._buffer;
  28544. };
  28545. /**
  28546. * Gets the stride in float32 units (i.e. byte stride / 4).
  28547. * May not be an integer if the byte stride is not divisible by 4.
  28548. * DEPRECATED. Use byteStride instead.
  28549. * @returns the stride in float32 units
  28550. */
  28551. Buffer.prototype.getStrideSize = function () {
  28552. return this.byteStride / 4;
  28553. };
  28554. // Methods
  28555. Buffer.prototype.create = function (data) {
  28556. if (data === void 0) { data = null; }
  28557. if (!data && this._buffer) {
  28558. return; // nothing to do
  28559. }
  28560. data = data || this._data;
  28561. if (!data) {
  28562. return;
  28563. }
  28564. if (!this._buffer) {
  28565. if (this._updatable) {
  28566. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28567. this._data = data;
  28568. }
  28569. else {
  28570. this._buffer = this._engine.createVertexBuffer(data);
  28571. }
  28572. }
  28573. else if (this._updatable) {
  28574. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28575. this._data = data;
  28576. }
  28577. };
  28578. Buffer.prototype._rebuild = function () {
  28579. this._buffer = null;
  28580. this.create(this._data);
  28581. };
  28582. Buffer.prototype.update = function (data) {
  28583. this.create(data);
  28584. };
  28585. /**
  28586. * Updates the data directly.
  28587. * @param data the new data
  28588. * @param offset the new offset
  28589. * @param vertexCount the vertex count (optional)
  28590. * @param useBytes set to true if the offset is in bytes
  28591. */
  28592. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28593. if (useBytes === void 0) { useBytes = false; }
  28594. if (!this._buffer) {
  28595. return;
  28596. }
  28597. if (this._updatable) {
  28598. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * 4, (vertexCount ? vertexCount * this.byteStride : undefined));
  28599. this._data = null;
  28600. }
  28601. };
  28602. Buffer.prototype.dispose = function () {
  28603. if (!this._buffer) {
  28604. return;
  28605. }
  28606. if (this._engine._releaseBuffer(this._buffer)) {
  28607. this._buffer = null;
  28608. }
  28609. };
  28610. return Buffer;
  28611. }());
  28612. BABYLON.Buffer = Buffer;
  28613. })(BABYLON || (BABYLON = {}));
  28614. //# sourceMappingURL=babylon.buffer.js.map
  28615. "use strict";
  28616. var BABYLON;
  28617. (function (BABYLON) {
  28618. var VertexBuffer = /** @class */ (function () {
  28619. /**
  28620. * Constructor
  28621. * @param engine the engine
  28622. * @param data the data to use for this vertex buffer
  28623. * @param kind the vertex buffer kind
  28624. * @param updatable whether the data is updatable
  28625. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28626. * @param stride the stride (optional)
  28627. * @param instanced whether the buffer is instanced (optional)
  28628. * @param offset the offset of the data (optional)
  28629. * @param size the number of components (optional)
  28630. * @param type the type of the component (optional)
  28631. * @param normalized whether the data contains normalized data (optional)
  28632. * @param useBytes set to true if stride and offset are in bytes (optional)
  28633. */
  28634. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28635. if (normalized === void 0) { normalized = false; }
  28636. if (useBytes === void 0) { useBytes = false; }
  28637. if (data instanceof BABYLON.Buffer) {
  28638. this._buffer = data;
  28639. this._ownsBuffer = false;
  28640. }
  28641. else {
  28642. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28643. this._ownsBuffer = true;
  28644. }
  28645. this._kind = kind;
  28646. if (type == undefined) {
  28647. var data_1 = this.getData();
  28648. this.type = VertexBuffer.FLOAT;
  28649. if (data_1 instanceof Int8Array)
  28650. this.type = VertexBuffer.BYTE;
  28651. else if (data_1 instanceof Uint8Array)
  28652. this.type = VertexBuffer.UNSIGNED_BYTE;
  28653. else if (data_1 instanceof Int16Array)
  28654. this.type = VertexBuffer.SHORT;
  28655. else if (data_1 instanceof Uint16Array)
  28656. this.type = VertexBuffer.UNSIGNED_SHORT;
  28657. else if (data_1 instanceof Int32Array)
  28658. this.type = VertexBuffer.INT;
  28659. else if (data_1 instanceof Uint32Array)
  28660. this.type = VertexBuffer.UNSIGNED_INT;
  28661. }
  28662. else {
  28663. this.type = type;
  28664. }
  28665. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28666. if (useBytes) {
  28667. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28668. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28669. this.byteOffset = offset || 0;
  28670. }
  28671. else {
  28672. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28673. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28674. this.byteOffset = (offset || 0) * typeByteLength;
  28675. }
  28676. this.normalized = normalized;
  28677. this._instanced = instanced !== undefined ? instanced : false;
  28678. this._instanceDivisor = instanced ? 1 : 0;
  28679. }
  28680. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28681. /**
  28682. * Gets or sets the instance divisor when in instanced mode
  28683. */
  28684. get: function () {
  28685. return this._instanceDivisor;
  28686. },
  28687. set: function (value) {
  28688. this._instanceDivisor = value;
  28689. if (value == 0) {
  28690. this._instanced = false;
  28691. }
  28692. else {
  28693. this._instanced = true;
  28694. }
  28695. },
  28696. enumerable: true,
  28697. configurable: true
  28698. });
  28699. VertexBuffer.prototype._rebuild = function () {
  28700. if (!this._buffer) {
  28701. return;
  28702. }
  28703. this._buffer._rebuild();
  28704. };
  28705. /**
  28706. * Returns the kind of the VertexBuffer (string).
  28707. */
  28708. VertexBuffer.prototype.getKind = function () {
  28709. return this._kind;
  28710. };
  28711. // Properties
  28712. /**
  28713. * Boolean : is the VertexBuffer updatable ?
  28714. */
  28715. VertexBuffer.prototype.isUpdatable = function () {
  28716. return this._buffer.isUpdatable();
  28717. };
  28718. /**
  28719. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28720. */
  28721. VertexBuffer.prototype.getData = function () {
  28722. return this._buffer.getData();
  28723. };
  28724. /**
  28725. * Returns the WebGLBuffer associated to the VertexBuffer.
  28726. */
  28727. VertexBuffer.prototype.getBuffer = function () {
  28728. return this._buffer.getBuffer();
  28729. };
  28730. /**
  28731. * Returns the stride as a multiple of the type byte length.
  28732. * DEPRECATED. Use byteStride instead.
  28733. */
  28734. VertexBuffer.prototype.getStrideSize = function () {
  28735. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28736. };
  28737. /**
  28738. * Returns the offset as a multiple of the type byte length.
  28739. * DEPRECATED. Use byteOffset instead.
  28740. */
  28741. VertexBuffer.prototype.getOffset = function () {
  28742. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28743. };
  28744. /**
  28745. * Returns the number of components per vertex attribute (integer).
  28746. */
  28747. VertexBuffer.prototype.getSize = function () {
  28748. return this._size;
  28749. };
  28750. /**
  28751. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28752. */
  28753. VertexBuffer.prototype.getIsInstanced = function () {
  28754. return this._instanced;
  28755. };
  28756. /**
  28757. * Returns the instancing divisor, zero for non-instanced (integer).
  28758. */
  28759. VertexBuffer.prototype.getInstanceDivisor = function () {
  28760. return this._instanceDivisor;
  28761. };
  28762. // Methods
  28763. /**
  28764. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28765. * Returns the created WebGLBuffer.
  28766. */
  28767. VertexBuffer.prototype.create = function (data) {
  28768. return this._buffer.create(data);
  28769. };
  28770. /**
  28771. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28772. * This function will create a new buffer if the current one is not updatable
  28773. * Returns the updated WebGLBuffer.
  28774. */
  28775. VertexBuffer.prototype.update = function (data) {
  28776. return this._buffer.update(data);
  28777. };
  28778. /**
  28779. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28780. * Returns the directly updated WebGLBuffer.
  28781. */
  28782. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  28783. return this._buffer.updateDirectly(data, offset);
  28784. };
  28785. /**
  28786. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28787. */
  28788. VertexBuffer.prototype.dispose = function () {
  28789. if (this._ownsBuffer) {
  28790. this._buffer.dispose();
  28791. }
  28792. };
  28793. /**
  28794. * Enumerates each value of this vertex buffer as numbers.
  28795. * @param count the number of values to enumerate
  28796. * @param callback the callback function called for each value
  28797. */
  28798. VertexBuffer.prototype.forEach = function (count, callback) {
  28799. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28800. };
  28801. Object.defineProperty(VertexBuffer, "PositionKind", {
  28802. get: function () {
  28803. return VertexBuffer._PositionKind;
  28804. },
  28805. enumerable: true,
  28806. configurable: true
  28807. });
  28808. Object.defineProperty(VertexBuffer, "NormalKind", {
  28809. get: function () {
  28810. return VertexBuffer._NormalKind;
  28811. },
  28812. enumerable: true,
  28813. configurable: true
  28814. });
  28815. Object.defineProperty(VertexBuffer, "TangentKind", {
  28816. get: function () {
  28817. return VertexBuffer._TangentKind;
  28818. },
  28819. enumerable: true,
  28820. configurable: true
  28821. });
  28822. Object.defineProperty(VertexBuffer, "UVKind", {
  28823. get: function () {
  28824. return VertexBuffer._UVKind;
  28825. },
  28826. enumerable: true,
  28827. configurable: true
  28828. });
  28829. Object.defineProperty(VertexBuffer, "UV2Kind", {
  28830. get: function () {
  28831. return VertexBuffer._UV2Kind;
  28832. },
  28833. enumerable: true,
  28834. configurable: true
  28835. });
  28836. Object.defineProperty(VertexBuffer, "UV3Kind", {
  28837. get: function () {
  28838. return VertexBuffer._UV3Kind;
  28839. },
  28840. enumerable: true,
  28841. configurable: true
  28842. });
  28843. Object.defineProperty(VertexBuffer, "UV4Kind", {
  28844. get: function () {
  28845. return VertexBuffer._UV4Kind;
  28846. },
  28847. enumerable: true,
  28848. configurable: true
  28849. });
  28850. Object.defineProperty(VertexBuffer, "UV5Kind", {
  28851. get: function () {
  28852. return VertexBuffer._UV5Kind;
  28853. },
  28854. enumerable: true,
  28855. configurable: true
  28856. });
  28857. Object.defineProperty(VertexBuffer, "UV6Kind", {
  28858. get: function () {
  28859. return VertexBuffer._UV6Kind;
  28860. },
  28861. enumerable: true,
  28862. configurable: true
  28863. });
  28864. Object.defineProperty(VertexBuffer, "ColorKind", {
  28865. get: function () {
  28866. return VertexBuffer._ColorKind;
  28867. },
  28868. enumerable: true,
  28869. configurable: true
  28870. });
  28871. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  28872. get: function () {
  28873. return VertexBuffer._MatricesIndicesKind;
  28874. },
  28875. enumerable: true,
  28876. configurable: true
  28877. });
  28878. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  28879. get: function () {
  28880. return VertexBuffer._MatricesWeightsKind;
  28881. },
  28882. enumerable: true,
  28883. configurable: true
  28884. });
  28885. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  28886. get: function () {
  28887. return VertexBuffer._MatricesIndicesExtraKind;
  28888. },
  28889. enumerable: true,
  28890. configurable: true
  28891. });
  28892. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  28893. get: function () {
  28894. return VertexBuffer._MatricesWeightsExtraKind;
  28895. },
  28896. enumerable: true,
  28897. configurable: true
  28898. });
  28899. /**
  28900. * Deduces the stride given a kind.
  28901. * @param kind The kind string to deduce
  28902. * @returns The deduced stride
  28903. */
  28904. VertexBuffer.DeduceStride = function (kind) {
  28905. switch (kind) {
  28906. case VertexBuffer.UVKind:
  28907. case VertexBuffer.UV2Kind:
  28908. case VertexBuffer.UV3Kind:
  28909. case VertexBuffer.UV4Kind:
  28910. case VertexBuffer.UV5Kind:
  28911. case VertexBuffer.UV6Kind:
  28912. return 2;
  28913. case VertexBuffer.NormalKind:
  28914. case VertexBuffer.PositionKind:
  28915. return 3;
  28916. case VertexBuffer.ColorKind:
  28917. case VertexBuffer.MatricesIndicesKind:
  28918. case VertexBuffer.MatricesIndicesExtraKind:
  28919. case VertexBuffer.MatricesWeightsKind:
  28920. case VertexBuffer.MatricesWeightsExtraKind:
  28921. case VertexBuffer.TangentKind:
  28922. return 4;
  28923. default:
  28924. throw new Error("Invalid kind '" + kind + "'");
  28925. }
  28926. };
  28927. /**
  28928. * Gets the byte length of the given type.
  28929. * @param type the type
  28930. * @returns the number of bytes
  28931. */
  28932. VertexBuffer.GetTypeByteLength = function (type) {
  28933. switch (type) {
  28934. case VertexBuffer.BYTE:
  28935. case VertexBuffer.UNSIGNED_BYTE:
  28936. return 1;
  28937. case VertexBuffer.SHORT:
  28938. case VertexBuffer.UNSIGNED_SHORT:
  28939. return 2;
  28940. case VertexBuffer.INT:
  28941. case VertexBuffer.FLOAT:
  28942. return 4;
  28943. default:
  28944. throw new Error("Invalid type '" + type + "'");
  28945. }
  28946. };
  28947. /**
  28948. * Enumerates each value of the given parameters as numbers.
  28949. * @param data the data to enumerate
  28950. * @param byteOffset the byte offset of the data
  28951. * @param byteStride the byte stride of the data
  28952. * @param componentCount the number of components per element
  28953. * @param componentType the type of the component
  28954. * @param count the total number of components
  28955. * @param normalized whether the data is normalized
  28956. * @param callback the callback function called for each value
  28957. */
  28958. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  28959. if (data instanceof Array) {
  28960. var offset = byteOffset / 4;
  28961. var stride = byteStride / 4;
  28962. for (var index = 0; index < count; index += componentCount) {
  28963. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  28964. callback(data[offset + componentIndex], index + componentIndex);
  28965. }
  28966. offset += stride;
  28967. }
  28968. }
  28969. else {
  28970. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  28971. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  28972. for (var index = 0; index < count; index += componentCount) {
  28973. var componentByteOffset = byteOffset;
  28974. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  28975. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  28976. callback(value, index + componentIndex);
  28977. componentByteOffset += componentByteLength;
  28978. }
  28979. byteOffset += byteStride;
  28980. }
  28981. }
  28982. };
  28983. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  28984. switch (type) {
  28985. case VertexBuffer.BYTE: {
  28986. var value = dataView.getInt8(byteOffset);
  28987. if (normalized) {
  28988. value = (value + 0.5) / 127.5;
  28989. }
  28990. return value;
  28991. }
  28992. case VertexBuffer.UNSIGNED_BYTE: {
  28993. var value = dataView.getUint8(byteOffset);
  28994. if (normalized) {
  28995. value = value / 255;
  28996. }
  28997. return value;
  28998. }
  28999. case VertexBuffer.SHORT: {
  29000. var value = dataView.getInt16(byteOffset, true);
  29001. if (normalized) {
  29002. value = (value + 0.5) / 16383.5;
  29003. }
  29004. return value;
  29005. }
  29006. case VertexBuffer.UNSIGNED_SHORT: {
  29007. var value = dataView.getUint16(byteOffset, true);
  29008. if (normalized) {
  29009. value = value / 65535;
  29010. }
  29011. return value;
  29012. }
  29013. case VertexBuffer.FLOAT: {
  29014. return dataView.getFloat32(byteOffset, true);
  29015. }
  29016. default: {
  29017. throw new Error("Invalid component type " + type);
  29018. }
  29019. }
  29020. };
  29021. /**
  29022. * The byte type.
  29023. */
  29024. VertexBuffer.BYTE = 5120;
  29025. /**
  29026. * The unsigned byte type.
  29027. */
  29028. VertexBuffer.UNSIGNED_BYTE = 5121;
  29029. /**
  29030. * The short type.
  29031. */
  29032. VertexBuffer.SHORT = 5122;
  29033. /**
  29034. * The unsigned short type.
  29035. */
  29036. VertexBuffer.UNSIGNED_SHORT = 5123;
  29037. /**
  29038. * The integer type.
  29039. */
  29040. VertexBuffer.INT = 5124;
  29041. /**
  29042. * The unsigned integer type.
  29043. */
  29044. VertexBuffer.UNSIGNED_INT = 5125;
  29045. /**
  29046. * The float type.
  29047. */
  29048. VertexBuffer.FLOAT = 5126;
  29049. // Enums
  29050. VertexBuffer._PositionKind = "position";
  29051. VertexBuffer._NormalKind = "normal";
  29052. VertexBuffer._TangentKind = "tangent";
  29053. VertexBuffer._UVKind = "uv";
  29054. VertexBuffer._UV2Kind = "uv2";
  29055. VertexBuffer._UV3Kind = "uv3";
  29056. VertexBuffer._UV4Kind = "uv4";
  29057. VertexBuffer._UV5Kind = "uv5";
  29058. VertexBuffer._UV6Kind = "uv6";
  29059. VertexBuffer._ColorKind = "color";
  29060. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29061. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29062. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29063. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29064. return VertexBuffer;
  29065. }());
  29066. BABYLON.VertexBuffer = VertexBuffer;
  29067. })(BABYLON || (BABYLON = {}));
  29068. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29069. "use strict";
  29070. var BABYLON;
  29071. (function (BABYLON) {
  29072. /**
  29073. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29074. */
  29075. var DummyInternalTextureTracker = /** @class */ (function () {
  29076. function DummyInternalTextureTracker() {
  29077. /**
  29078. * Gets or set the previous tracker in the list
  29079. */
  29080. this.previous = null;
  29081. /**
  29082. * Gets or set the next tracker in the list
  29083. */
  29084. this.next = null;
  29085. }
  29086. return DummyInternalTextureTracker;
  29087. }());
  29088. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29089. })(BABYLON || (BABYLON = {}));
  29090. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29091. "use strict";
  29092. var BABYLON;
  29093. (function (BABYLON) {
  29094. /**
  29095. * Class used to store data associated with WebGL texture data for the engine
  29096. * This class should not be used directly
  29097. */
  29098. var InternalTexture = /** @class */ (function () {
  29099. /**
  29100. * Creates a new InternalTexture
  29101. * @param engine defines the engine to use
  29102. * @param dataSource defines the type of data that will be used
  29103. */
  29104. function InternalTexture(engine, dataSource) {
  29105. /**
  29106. * Observable called when the texture is loaded
  29107. */
  29108. this.onLoadedObservable = new BABYLON.Observable();
  29109. /**
  29110. * Gets or set the previous tracker in the list
  29111. */
  29112. this.previous = null;
  29113. /**
  29114. * Gets or set the next tracker in the list
  29115. */
  29116. this.next = null;
  29117. // Private
  29118. /** @ignore */
  29119. this._initialSlot = -1;
  29120. /** @ignore */
  29121. this._designatedSlot = -1;
  29122. /** @ignore */
  29123. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29124. /** @ignore */
  29125. this._comparisonFunction = 0;
  29126. /** @ignore */
  29127. this._references = 1;
  29128. this._engine = engine;
  29129. this._dataSource = dataSource;
  29130. this._webGLTexture = engine._createTexture();
  29131. }
  29132. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29133. /**
  29134. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29135. */
  29136. get: function () {
  29137. return this._dataSource;
  29138. },
  29139. enumerable: true,
  29140. configurable: true
  29141. });
  29142. /**
  29143. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29144. */
  29145. InternalTexture.prototype.incrementReferences = function () {
  29146. this._references++;
  29147. };
  29148. /**
  29149. * Change the size of the texture (not the size of the content)
  29150. * @param width defines the new width
  29151. * @param height defines the new height
  29152. * @param depth defines the new depth (1 by default)
  29153. */
  29154. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29155. if (depth === void 0) { depth = 1; }
  29156. this.width = width;
  29157. this.height = height;
  29158. this.depth = depth;
  29159. this.baseWidth = width;
  29160. this.baseHeight = height;
  29161. this.baseDepth = depth;
  29162. this._size = width * height * depth;
  29163. };
  29164. /** @ignore */
  29165. InternalTexture.prototype._rebuild = function () {
  29166. var _this = this;
  29167. var proxy;
  29168. this.isReady = false;
  29169. this._cachedCoordinatesMode = null;
  29170. this._cachedWrapU = null;
  29171. this._cachedWrapV = null;
  29172. this._cachedAnisotropicFilteringLevel = null;
  29173. switch (this._dataSource) {
  29174. case InternalTexture.DATASOURCE_TEMP:
  29175. return;
  29176. case InternalTexture.DATASOURCE_URL:
  29177. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29178. _this.isReady = true;
  29179. }, null, this._buffer, undefined, this.format);
  29180. proxy._swapAndDie(this);
  29181. return;
  29182. case InternalTexture.DATASOURCE_RAW:
  29183. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29184. proxy._swapAndDie(this);
  29185. this.isReady = true;
  29186. return;
  29187. case InternalTexture.DATASOURCE_RAW3D:
  29188. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29189. proxy._swapAndDie(this);
  29190. this.isReady = true;
  29191. return;
  29192. case InternalTexture.DATASOURCE_DYNAMIC:
  29193. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29194. proxy._swapAndDie(this);
  29195. // The engine will make sure to update content so no need to flag it as isReady = true
  29196. return;
  29197. case InternalTexture.DATASOURCE_RENDERTARGET:
  29198. var options = new BABYLON.RenderTargetCreationOptions();
  29199. options.generateDepthBuffer = this._generateDepthBuffer;
  29200. options.generateMipMaps = this.generateMipMaps;
  29201. options.generateStencilBuffer = this._generateStencilBuffer;
  29202. options.samplingMode = this.samplingMode;
  29203. options.type = this.type;
  29204. if (this.isCube) {
  29205. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29206. }
  29207. else {
  29208. var size = {
  29209. width: this.width,
  29210. height: this.height
  29211. };
  29212. proxy = this._engine.createRenderTargetTexture(size, options);
  29213. }
  29214. proxy._swapAndDie(this);
  29215. this.isReady = true;
  29216. return;
  29217. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29218. var depthTextureOptions = {
  29219. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29220. comparisonFunction: this._comparisonFunction,
  29221. generateStencil: this._generateStencilBuffer,
  29222. isCube: this.isCube
  29223. };
  29224. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29225. proxy._swapAndDie(this);
  29226. this.isReady = true;
  29227. return;
  29228. case InternalTexture.DATASOURCE_CUBE:
  29229. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29230. _this.isReady = true;
  29231. }, null, this.format, this._extension);
  29232. proxy._swapAndDie(this);
  29233. return;
  29234. case InternalTexture.DATASOURCE_CUBERAW:
  29235. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29236. proxy._swapAndDie(this);
  29237. this.isReady = true;
  29238. return;
  29239. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29240. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29241. if (proxy) {
  29242. proxy._swapAndDie(_this);
  29243. }
  29244. _this.isReady = true;
  29245. }, null, this.format, this._extension);
  29246. return;
  29247. }
  29248. };
  29249. InternalTexture.prototype._swapAndDie = function (target) {
  29250. target._webGLTexture = this._webGLTexture;
  29251. if (this._framebuffer) {
  29252. target._framebuffer = this._framebuffer;
  29253. }
  29254. if (this._depthStencilBuffer) {
  29255. target._depthStencilBuffer = this._depthStencilBuffer;
  29256. }
  29257. if (this._lodTextureHigh) {
  29258. if (target._lodTextureHigh) {
  29259. target._lodTextureHigh.dispose();
  29260. }
  29261. target._lodTextureHigh = this._lodTextureHigh;
  29262. }
  29263. if (this._lodTextureMid) {
  29264. if (target._lodTextureMid) {
  29265. target._lodTextureMid.dispose();
  29266. }
  29267. target._lodTextureMid = this._lodTextureMid;
  29268. }
  29269. if (this._lodTextureLow) {
  29270. if (target._lodTextureLow) {
  29271. target._lodTextureLow.dispose();
  29272. }
  29273. target._lodTextureLow = this._lodTextureLow;
  29274. }
  29275. var cache = this._engine.getLoadedTexturesCache();
  29276. var index = cache.indexOf(this);
  29277. if (index !== -1) {
  29278. cache.splice(index, 1);
  29279. }
  29280. };
  29281. /**
  29282. * Dispose the current allocated resources
  29283. */
  29284. InternalTexture.prototype.dispose = function () {
  29285. if (!this._webGLTexture) {
  29286. return;
  29287. }
  29288. this._references--;
  29289. if (this._references === 0) {
  29290. this._engine._releaseTexture(this);
  29291. this._webGLTexture = null;
  29292. this.previous = null;
  29293. this.next = null;
  29294. }
  29295. };
  29296. /**
  29297. * The source of the texture data is unknown
  29298. */
  29299. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29300. /**
  29301. * Texture data comes from an URL
  29302. */
  29303. InternalTexture.DATASOURCE_URL = 1;
  29304. /**
  29305. * Texture data is only used for temporary storage
  29306. */
  29307. InternalTexture.DATASOURCE_TEMP = 2;
  29308. /**
  29309. * Texture data comes from raw data (ArrayBuffer)
  29310. */
  29311. InternalTexture.DATASOURCE_RAW = 3;
  29312. /**
  29313. * Texture content is dynamic (video or dynamic texture)
  29314. */
  29315. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29316. /**
  29317. * Texture content is generated by rendering to it
  29318. */
  29319. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29320. /**
  29321. * Texture content is part of a multi render target process
  29322. */
  29323. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29324. /**
  29325. * Texture data comes from a cube data file
  29326. */
  29327. InternalTexture.DATASOURCE_CUBE = 7;
  29328. /**
  29329. * Texture data comes from a raw cube data
  29330. */
  29331. InternalTexture.DATASOURCE_CUBERAW = 8;
  29332. /**
  29333. * Texture data come from a prefiltered cube data file
  29334. */
  29335. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29336. /**
  29337. * Texture content is raw 3D data
  29338. */
  29339. InternalTexture.DATASOURCE_RAW3D = 10;
  29340. /**
  29341. * Texture content is a depth texture
  29342. */
  29343. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29344. return InternalTexture;
  29345. }());
  29346. BABYLON.InternalTexture = InternalTexture;
  29347. })(BABYLON || (BABYLON = {}));
  29348. //# sourceMappingURL=babylon.internalTexture.js.map
  29349. "use strict";
  29350. var BABYLON;
  29351. (function (BABYLON) {
  29352. var BaseTexture = /** @class */ (function () {
  29353. function BaseTexture(scene) {
  29354. this._hasAlpha = false;
  29355. this.getAlphaFromRGB = false;
  29356. this.level = 1;
  29357. this.coordinatesIndex = 0;
  29358. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29359. /**
  29360. * | Value | Type | Description |
  29361. * | ----- | ------------------ | ----------- |
  29362. * | 0 | CLAMP_ADDRESSMODE | |
  29363. * | 1 | WRAP_ADDRESSMODE | |
  29364. * | 2 | MIRROR_ADDRESSMODE | |
  29365. */
  29366. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29367. /**
  29368. * | Value | Type | Description |
  29369. * | ----- | ------------------ | ----------- |
  29370. * | 0 | CLAMP_ADDRESSMODE | |
  29371. * | 1 | WRAP_ADDRESSMODE | |
  29372. * | 2 | MIRROR_ADDRESSMODE | |
  29373. */
  29374. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29375. /**
  29376. * | Value | Type | Description |
  29377. * | ----- | ------------------ | ----------- |
  29378. * | 0 | CLAMP_ADDRESSMODE | |
  29379. * | 1 | WRAP_ADDRESSMODE | |
  29380. * | 2 | MIRROR_ADDRESSMODE | |
  29381. */
  29382. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29383. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29384. this.isCube = false;
  29385. this.is3D = false;
  29386. this.gammaSpace = true;
  29387. this.invertZ = false;
  29388. this.lodLevelInAlpha = false;
  29389. this.lodGenerationOffset = 0.0;
  29390. this.lodGenerationScale = 0.8;
  29391. this.isRenderTarget = false;
  29392. this.animations = new Array();
  29393. /**
  29394. * An event triggered when the texture is disposed.
  29395. */
  29396. this.onDisposeObservable = new BABYLON.Observable();
  29397. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29398. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29399. if (this._scene) {
  29400. this._scene.textures.push(this);
  29401. }
  29402. this._uid = null;
  29403. }
  29404. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29405. get: function () {
  29406. return this._hasAlpha;
  29407. },
  29408. set: function (value) {
  29409. if (this._hasAlpha === value) {
  29410. return;
  29411. }
  29412. this._hasAlpha = value;
  29413. if (this._scene) {
  29414. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29415. }
  29416. },
  29417. enumerable: true,
  29418. configurable: true
  29419. });
  29420. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29421. get: function () {
  29422. return this._coordinatesMode;
  29423. },
  29424. /**
  29425. * How a texture is mapped.
  29426. *
  29427. * | Value | Type | Description |
  29428. * | ----- | ----------------------------------- | ----------- |
  29429. * | 0 | EXPLICIT_MODE | |
  29430. * | 1 | SPHERICAL_MODE | |
  29431. * | 2 | PLANAR_MODE | |
  29432. * | 3 | CUBIC_MODE | |
  29433. * | 4 | PROJECTION_MODE | |
  29434. * | 5 | SKYBOX_MODE | |
  29435. * | 6 | INVCUBIC_MODE | |
  29436. * | 7 | EQUIRECTANGULAR_MODE | |
  29437. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29438. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29439. */
  29440. set: function (value) {
  29441. if (this._coordinatesMode === value) {
  29442. return;
  29443. }
  29444. this._coordinatesMode = value;
  29445. if (this._scene) {
  29446. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29447. }
  29448. },
  29449. enumerable: true,
  29450. configurable: true
  29451. });
  29452. Object.defineProperty(BaseTexture.prototype, "uid", {
  29453. get: function () {
  29454. if (!this._uid) {
  29455. this._uid = BABYLON.Tools.RandomId();
  29456. }
  29457. return this._uid;
  29458. },
  29459. enumerable: true,
  29460. configurable: true
  29461. });
  29462. BaseTexture.prototype.toString = function () {
  29463. return this.name;
  29464. };
  29465. BaseTexture.prototype.getClassName = function () {
  29466. return "BaseTexture";
  29467. };
  29468. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29469. set: function (callback) {
  29470. if (this._onDisposeObserver) {
  29471. this.onDisposeObservable.remove(this._onDisposeObserver);
  29472. }
  29473. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29474. },
  29475. enumerable: true,
  29476. configurable: true
  29477. });
  29478. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29479. get: function () {
  29480. return true;
  29481. },
  29482. enumerable: true,
  29483. configurable: true
  29484. });
  29485. BaseTexture.prototype.getScene = function () {
  29486. return this._scene;
  29487. };
  29488. BaseTexture.prototype.getTextureMatrix = function () {
  29489. return BABYLON.Matrix.IdentityReadOnly;
  29490. };
  29491. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29492. return BABYLON.Matrix.IdentityReadOnly;
  29493. };
  29494. BaseTexture.prototype.getInternalTexture = function () {
  29495. return this._texture;
  29496. };
  29497. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29498. return !this.isBlocking || this.isReady();
  29499. };
  29500. BaseTexture.prototype.isReady = function () {
  29501. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29502. this.delayLoad();
  29503. return false;
  29504. }
  29505. if (this._texture) {
  29506. return this._texture.isReady;
  29507. }
  29508. return false;
  29509. };
  29510. BaseTexture.prototype.getSize = function () {
  29511. if (this._texture && this._texture.width) {
  29512. return new BABYLON.Size(this._texture.width, this._texture.height);
  29513. }
  29514. if (this._texture && this._texture._size) {
  29515. return new BABYLON.Size(this._texture._size, this._texture._size);
  29516. }
  29517. return BABYLON.Size.Zero();
  29518. };
  29519. BaseTexture.prototype.getBaseSize = function () {
  29520. if (!this.isReady() || !this._texture)
  29521. return BABYLON.Size.Zero();
  29522. if (this._texture._size) {
  29523. return new BABYLON.Size(this._texture._size, this._texture._size);
  29524. }
  29525. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29526. };
  29527. BaseTexture.prototype.scale = function (ratio) {
  29528. };
  29529. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29530. get: function () {
  29531. return false;
  29532. },
  29533. enumerable: true,
  29534. configurable: true
  29535. });
  29536. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29537. if (!this._scene) {
  29538. return null;
  29539. }
  29540. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29541. for (var index = 0; index < texturesCache.length; index++) {
  29542. var texturesCacheEntry = texturesCache[index];
  29543. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29544. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29545. texturesCacheEntry.incrementReferences();
  29546. return texturesCacheEntry;
  29547. }
  29548. }
  29549. }
  29550. return null;
  29551. };
  29552. BaseTexture.prototype._rebuild = function () {
  29553. };
  29554. BaseTexture.prototype.delayLoad = function () {
  29555. };
  29556. BaseTexture.prototype.clone = function () {
  29557. return null;
  29558. };
  29559. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29560. get: function () {
  29561. if (!this._texture) {
  29562. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29563. }
  29564. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29565. },
  29566. enumerable: true,
  29567. configurable: true
  29568. });
  29569. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29570. get: function () {
  29571. if (!this._texture) {
  29572. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29573. }
  29574. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29575. },
  29576. enumerable: true,
  29577. configurable: true
  29578. });
  29579. BaseTexture.prototype.readPixels = function (faceIndex) {
  29580. if (faceIndex === void 0) { faceIndex = 0; }
  29581. if (!this._texture) {
  29582. return null;
  29583. }
  29584. var size = this.getSize();
  29585. var scene = this.getScene();
  29586. if (!scene) {
  29587. return null;
  29588. }
  29589. var engine = scene.getEngine();
  29590. if (this._texture.isCube) {
  29591. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29592. }
  29593. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29594. };
  29595. BaseTexture.prototype.releaseInternalTexture = function () {
  29596. if (this._texture) {
  29597. this._texture.dispose();
  29598. this._texture = null;
  29599. }
  29600. };
  29601. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29602. get: function () {
  29603. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29604. return null;
  29605. }
  29606. if (!this._texture._sphericalPolynomial) {
  29607. this._texture._sphericalPolynomial =
  29608. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29609. }
  29610. return this._texture._sphericalPolynomial;
  29611. },
  29612. set: function (value) {
  29613. if (this._texture) {
  29614. this._texture._sphericalPolynomial = value;
  29615. }
  29616. },
  29617. enumerable: true,
  29618. configurable: true
  29619. });
  29620. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29621. get: function () {
  29622. if (this._texture) {
  29623. return this._texture._lodTextureHigh;
  29624. }
  29625. return null;
  29626. },
  29627. enumerable: true,
  29628. configurable: true
  29629. });
  29630. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29631. get: function () {
  29632. if (this._texture) {
  29633. return this._texture._lodTextureMid;
  29634. }
  29635. return null;
  29636. },
  29637. enumerable: true,
  29638. configurable: true
  29639. });
  29640. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29641. get: function () {
  29642. if (this._texture) {
  29643. return this._texture._lodTextureLow;
  29644. }
  29645. return null;
  29646. },
  29647. enumerable: true,
  29648. configurable: true
  29649. });
  29650. BaseTexture.prototype.dispose = function () {
  29651. if (!this._scene) {
  29652. return;
  29653. }
  29654. // Animations
  29655. this._scene.stopAnimation(this);
  29656. // Remove from scene
  29657. this._scene._removePendingData(this);
  29658. var index = this._scene.textures.indexOf(this);
  29659. if (index >= 0) {
  29660. this._scene.textures.splice(index, 1);
  29661. }
  29662. if (this._texture === undefined) {
  29663. return;
  29664. }
  29665. // Release
  29666. this.releaseInternalTexture();
  29667. // Callback
  29668. this.onDisposeObservable.notifyObservers(this);
  29669. this.onDisposeObservable.clear();
  29670. };
  29671. BaseTexture.prototype.serialize = function () {
  29672. if (!this.name) {
  29673. return null;
  29674. }
  29675. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29676. // Animations
  29677. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29678. return serializationObject;
  29679. };
  29680. BaseTexture.WhenAllReady = function (textures, callback) {
  29681. var numRemaining = textures.length;
  29682. if (numRemaining === 0) {
  29683. callback();
  29684. return;
  29685. }
  29686. var _loop_1 = function () {
  29687. texture = textures[i];
  29688. if (texture.isReady()) {
  29689. if (--numRemaining === 0) {
  29690. callback();
  29691. }
  29692. }
  29693. else {
  29694. onLoadObservable = texture.onLoadObservable;
  29695. var onLoadCallback_1 = function () {
  29696. onLoadObservable.removeCallback(onLoadCallback_1);
  29697. if (--numRemaining === 0) {
  29698. callback();
  29699. }
  29700. };
  29701. onLoadObservable.add(onLoadCallback_1);
  29702. }
  29703. };
  29704. var texture, onLoadObservable;
  29705. for (var i = 0; i < textures.length; i++) {
  29706. _loop_1();
  29707. }
  29708. };
  29709. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29710. __decorate([
  29711. BABYLON.serialize()
  29712. ], BaseTexture.prototype, "name", void 0);
  29713. __decorate([
  29714. BABYLON.serialize("hasAlpha")
  29715. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29716. __decorate([
  29717. BABYLON.serialize()
  29718. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29719. __decorate([
  29720. BABYLON.serialize()
  29721. ], BaseTexture.prototype, "level", void 0);
  29722. __decorate([
  29723. BABYLON.serialize()
  29724. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29725. __decorate([
  29726. BABYLON.serialize("coordinatesMode")
  29727. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29728. __decorate([
  29729. BABYLON.serialize()
  29730. ], BaseTexture.prototype, "wrapU", void 0);
  29731. __decorate([
  29732. BABYLON.serialize()
  29733. ], BaseTexture.prototype, "wrapV", void 0);
  29734. __decorate([
  29735. BABYLON.serialize()
  29736. ], BaseTexture.prototype, "wrapR", void 0);
  29737. __decorate([
  29738. BABYLON.serialize()
  29739. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29740. __decorate([
  29741. BABYLON.serialize()
  29742. ], BaseTexture.prototype, "isCube", void 0);
  29743. __decorate([
  29744. BABYLON.serialize()
  29745. ], BaseTexture.prototype, "is3D", void 0);
  29746. __decorate([
  29747. BABYLON.serialize()
  29748. ], BaseTexture.prototype, "gammaSpace", void 0);
  29749. __decorate([
  29750. BABYLON.serialize()
  29751. ], BaseTexture.prototype, "invertZ", void 0);
  29752. __decorate([
  29753. BABYLON.serialize()
  29754. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29755. __decorate([
  29756. BABYLON.serialize()
  29757. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  29758. __decorate([
  29759. BABYLON.serialize()
  29760. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  29761. __decorate([
  29762. BABYLON.serialize()
  29763. ], BaseTexture.prototype, "isRenderTarget", void 0);
  29764. return BaseTexture;
  29765. }());
  29766. BABYLON.BaseTexture = BaseTexture;
  29767. })(BABYLON || (BABYLON = {}));
  29768. //# sourceMappingURL=babylon.baseTexture.js.map
  29769. "use strict";
  29770. var BABYLON;
  29771. (function (BABYLON) {
  29772. var Texture = /** @class */ (function (_super) {
  29773. __extends(Texture, _super);
  29774. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  29775. if (noMipmap === void 0) { noMipmap = false; }
  29776. if (invertY === void 0) { invertY = true; }
  29777. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29778. if (onLoad === void 0) { onLoad = null; }
  29779. if (onError === void 0) { onError = null; }
  29780. if (buffer === void 0) { buffer = null; }
  29781. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29782. var _this = _super.call(this, scene) || this;
  29783. _this.uOffset = 0;
  29784. _this.vOffset = 0;
  29785. _this.uScale = 1.0;
  29786. _this.vScale = 1.0;
  29787. _this.uAng = 0;
  29788. _this.vAng = 0;
  29789. _this.wAng = 0;
  29790. _this._isBlocking = true;
  29791. _this.name = url || "";
  29792. _this.url = url;
  29793. _this._noMipmap = noMipmap;
  29794. _this._invertY = invertY;
  29795. _this._samplingMode = samplingMode;
  29796. _this._buffer = buffer;
  29797. _this._deleteBuffer = deleteBuffer;
  29798. if (format) {
  29799. _this._format = format;
  29800. }
  29801. scene = _this.getScene();
  29802. if (!scene) {
  29803. return _this;
  29804. }
  29805. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  29806. var load = function () {
  29807. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  29808. _this.onLoadObservable.notifyObservers(_this);
  29809. }
  29810. if (onLoad) {
  29811. onLoad();
  29812. }
  29813. if (!_this.isBlocking && scene) {
  29814. scene.resetCachedMaterial();
  29815. }
  29816. };
  29817. if (!_this.url) {
  29818. _this._delayedOnLoad = load;
  29819. _this._delayedOnError = onError;
  29820. return _this;
  29821. }
  29822. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  29823. if (!_this._texture) {
  29824. if (!scene.useDelayedTextureLoading) {
  29825. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  29826. if (deleteBuffer) {
  29827. delete _this._buffer;
  29828. }
  29829. }
  29830. else {
  29831. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29832. _this._delayedOnLoad = load;
  29833. _this._delayedOnError = onError;
  29834. }
  29835. }
  29836. else {
  29837. if (_this._texture.isReady) {
  29838. BABYLON.Tools.SetImmediate(function () { return load(); });
  29839. }
  29840. else {
  29841. _this._texture.onLoadedObservable.add(load);
  29842. }
  29843. }
  29844. return _this;
  29845. }
  29846. Object.defineProperty(Texture.prototype, "noMipmap", {
  29847. get: function () {
  29848. return this._noMipmap;
  29849. },
  29850. enumerable: true,
  29851. configurable: true
  29852. });
  29853. Object.defineProperty(Texture.prototype, "isBlocking", {
  29854. get: function () {
  29855. return this._isBlocking;
  29856. },
  29857. set: function (value) {
  29858. this._isBlocking = value;
  29859. },
  29860. enumerable: true,
  29861. configurable: true
  29862. });
  29863. Object.defineProperty(Texture.prototype, "samplingMode", {
  29864. get: function () {
  29865. return this._samplingMode;
  29866. },
  29867. enumerable: true,
  29868. configurable: true
  29869. });
  29870. Texture.prototype.updateURL = function (url) {
  29871. this.url = url;
  29872. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29873. this.delayLoad();
  29874. };
  29875. Texture.prototype.delayLoad = function () {
  29876. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29877. return;
  29878. }
  29879. var scene = this.getScene();
  29880. if (!scene) {
  29881. return;
  29882. }
  29883. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29884. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  29885. if (!this._texture) {
  29886. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  29887. if (this._deleteBuffer) {
  29888. delete this._buffer;
  29889. }
  29890. }
  29891. else {
  29892. if (this._delayedOnLoad) {
  29893. if (this._texture.isReady) {
  29894. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  29895. }
  29896. else {
  29897. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  29898. }
  29899. }
  29900. }
  29901. this._delayedOnLoad = null;
  29902. this._delayedOnError = null;
  29903. };
  29904. Texture.prototype.updateSamplingMode = function (samplingMode) {
  29905. if (!this._texture) {
  29906. return;
  29907. }
  29908. var scene = this.getScene();
  29909. if (!scene) {
  29910. return;
  29911. }
  29912. this._samplingMode = samplingMode;
  29913. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  29914. };
  29915. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  29916. x *= this.uScale;
  29917. y *= this.vScale;
  29918. x -= 0.5 * this.uScale;
  29919. y -= 0.5 * this.vScale;
  29920. z -= 0.5;
  29921. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  29922. t.x += 0.5 * this.uScale + this.uOffset;
  29923. t.y += 0.5 * this.vScale + this.vOffset;
  29924. t.z += 0.5;
  29925. };
  29926. Texture.prototype.getTextureMatrix = function () {
  29927. var _this = this;
  29928. if (this.uOffset === this._cachedUOffset &&
  29929. this.vOffset === this._cachedVOffset &&
  29930. this.uScale === this._cachedUScale &&
  29931. this.vScale === this._cachedVScale &&
  29932. this.uAng === this._cachedUAng &&
  29933. this.vAng === this._cachedVAng &&
  29934. this.wAng === this._cachedWAng) {
  29935. return this._cachedTextureMatrix;
  29936. }
  29937. this._cachedUOffset = this.uOffset;
  29938. this._cachedVOffset = this.vOffset;
  29939. this._cachedUScale = this.uScale;
  29940. this._cachedVScale = this.vScale;
  29941. this._cachedUAng = this.uAng;
  29942. this._cachedVAng = this.vAng;
  29943. this._cachedWAng = this.wAng;
  29944. if (!this._cachedTextureMatrix) {
  29945. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  29946. this._rowGenerationMatrix = new BABYLON.Matrix();
  29947. this._t0 = BABYLON.Vector3.Zero();
  29948. this._t1 = BABYLON.Vector3.Zero();
  29949. this._t2 = BABYLON.Vector3.Zero();
  29950. }
  29951. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  29952. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  29953. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  29954. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  29955. this._t1.subtractInPlace(this._t0);
  29956. this._t2.subtractInPlace(this._t0);
  29957. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29958. this._cachedTextureMatrix.m[0] = this._t1.x;
  29959. this._cachedTextureMatrix.m[1] = this._t1.y;
  29960. this._cachedTextureMatrix.m[2] = this._t1.z;
  29961. this._cachedTextureMatrix.m[4] = this._t2.x;
  29962. this._cachedTextureMatrix.m[5] = this._t2.y;
  29963. this._cachedTextureMatrix.m[6] = this._t2.z;
  29964. this._cachedTextureMatrix.m[8] = this._t0.x;
  29965. this._cachedTextureMatrix.m[9] = this._t0.y;
  29966. this._cachedTextureMatrix.m[10] = this._t0.z;
  29967. var scene = this.getScene();
  29968. if (!scene) {
  29969. return this._cachedTextureMatrix;
  29970. }
  29971. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  29972. return mat.hasTexture(_this);
  29973. });
  29974. return this._cachedTextureMatrix;
  29975. };
  29976. Texture.prototype.getReflectionTextureMatrix = function () {
  29977. var _this = this;
  29978. var scene = this.getScene();
  29979. if (!scene) {
  29980. return this._cachedTextureMatrix;
  29981. }
  29982. if (this.uOffset === this._cachedUOffset &&
  29983. this.vOffset === this._cachedVOffset &&
  29984. this.uScale === this._cachedUScale &&
  29985. this.vScale === this._cachedVScale &&
  29986. this.coordinatesMode === this._cachedCoordinatesMode) {
  29987. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  29988. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  29989. return this._cachedTextureMatrix;
  29990. }
  29991. }
  29992. else {
  29993. return this._cachedTextureMatrix;
  29994. }
  29995. }
  29996. if (!this._cachedTextureMatrix) {
  29997. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  29998. }
  29999. if (!this._projectionModeMatrix) {
  30000. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30001. }
  30002. this._cachedUOffset = this.uOffset;
  30003. this._cachedVOffset = this.vOffset;
  30004. this._cachedUScale = this.uScale;
  30005. this._cachedVScale = this.vScale;
  30006. this._cachedCoordinatesMode = this.coordinatesMode;
  30007. switch (this.coordinatesMode) {
  30008. case Texture.PLANAR_MODE:
  30009. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30010. this._cachedTextureMatrix[0] = this.uScale;
  30011. this._cachedTextureMatrix[5] = this.vScale;
  30012. this._cachedTextureMatrix[12] = this.uOffset;
  30013. this._cachedTextureMatrix[13] = this.vOffset;
  30014. break;
  30015. case Texture.PROJECTION_MODE:
  30016. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30017. this._projectionModeMatrix.m[0] = 0.5;
  30018. this._projectionModeMatrix.m[5] = -0.5;
  30019. this._projectionModeMatrix.m[10] = 0.0;
  30020. this._projectionModeMatrix.m[12] = 0.5;
  30021. this._projectionModeMatrix.m[13] = 0.5;
  30022. this._projectionModeMatrix.m[14] = 1.0;
  30023. this._projectionModeMatrix.m[15] = 1.0;
  30024. var projectionMatrix = scene.getProjectionMatrix();
  30025. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30026. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30027. break;
  30028. default:
  30029. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30030. break;
  30031. }
  30032. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30033. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30034. });
  30035. return this._cachedTextureMatrix;
  30036. };
  30037. Texture.prototype.clone = function () {
  30038. var _this = this;
  30039. return BABYLON.SerializationHelper.Clone(function () {
  30040. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30041. }, this);
  30042. };
  30043. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30044. get: function () {
  30045. if (!this._onLoadObservable) {
  30046. this._onLoadObservable = new BABYLON.Observable();
  30047. }
  30048. return this._onLoadObservable;
  30049. },
  30050. enumerable: true,
  30051. configurable: true
  30052. });
  30053. Texture.prototype.serialize = function () {
  30054. var serializationObject = _super.prototype.serialize.call(this);
  30055. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30056. serializationObject.base64String = this._buffer;
  30057. serializationObject.name = serializationObject.name.replace("data:", "");
  30058. }
  30059. serializationObject.invertY = this._invertY;
  30060. serializationObject.samplingMode = this.samplingMode;
  30061. return serializationObject;
  30062. };
  30063. Texture.prototype.getClassName = function () {
  30064. return "Texture";
  30065. };
  30066. Texture.prototype.dispose = function () {
  30067. _super.prototype.dispose.call(this);
  30068. if (this.onLoadObservable) {
  30069. this.onLoadObservable.clear();
  30070. this._onLoadObservable = null;
  30071. }
  30072. this._delayedOnLoad = null;
  30073. this._delayedOnError = null;
  30074. };
  30075. // Statics
  30076. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30077. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30078. if (onLoad === void 0) { onLoad = null; }
  30079. if (onError === void 0) { onError = null; }
  30080. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30081. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30082. };
  30083. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30084. if (parsedTexture.customType) {
  30085. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30086. // Update Sampling Mode
  30087. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30088. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30089. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30090. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30091. }
  30092. }
  30093. return parsedCustomTexture;
  30094. }
  30095. if (parsedTexture.isCube) {
  30096. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30097. }
  30098. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30099. return null;
  30100. }
  30101. var texture = BABYLON.SerializationHelper.Parse(function () {
  30102. var generateMipMaps = true;
  30103. if (parsedTexture.noMipmap) {
  30104. generateMipMaps = false;
  30105. }
  30106. if (parsedTexture.mirrorPlane) {
  30107. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30108. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30109. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30110. return mirrorTexture;
  30111. }
  30112. else if (parsedTexture.isRenderTarget) {
  30113. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30114. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30115. return renderTargetTexture;
  30116. }
  30117. else {
  30118. var texture;
  30119. if (parsedTexture.base64String) {
  30120. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30121. }
  30122. else {
  30123. var url = rootUrl + parsedTexture.name;
  30124. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30125. url = parsedTexture.url;
  30126. }
  30127. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30128. }
  30129. return texture;
  30130. }
  30131. }, parsedTexture, scene);
  30132. // Update Sampling Mode
  30133. if (parsedTexture.samplingMode) {
  30134. var sampling = parsedTexture.samplingMode;
  30135. if (texture._samplingMode !== sampling) {
  30136. texture.updateSamplingMode(sampling);
  30137. }
  30138. }
  30139. // Animations
  30140. if (parsedTexture.animations) {
  30141. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30142. var parsedAnimation = parsedTexture.animations[animationIndex];
  30143. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30144. }
  30145. }
  30146. return texture;
  30147. };
  30148. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30149. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30150. if (noMipmap === void 0) { noMipmap = false; }
  30151. if (invertY === void 0) { invertY = true; }
  30152. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30153. if (onLoad === void 0) { onLoad = null; }
  30154. if (onError === void 0) { onError = null; }
  30155. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30156. if (name.substr(0, 5) !== "data:") {
  30157. name = "data:" + name;
  30158. }
  30159. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30160. };
  30161. // Constants
  30162. Texture.NEAREST_SAMPLINGMODE = 1;
  30163. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30164. Texture.BILINEAR_SAMPLINGMODE = 2;
  30165. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30166. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30167. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30168. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30169. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30170. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30171. Texture.NEAREST_LINEAR = 7;
  30172. Texture.NEAREST_NEAREST = 8;
  30173. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30174. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30175. Texture.LINEAR_LINEAR = 11;
  30176. Texture.LINEAR_NEAREST = 12;
  30177. Texture.EXPLICIT_MODE = 0;
  30178. Texture.SPHERICAL_MODE = 1;
  30179. Texture.PLANAR_MODE = 2;
  30180. Texture.CUBIC_MODE = 3;
  30181. Texture.PROJECTION_MODE = 4;
  30182. Texture.SKYBOX_MODE = 5;
  30183. Texture.INVCUBIC_MODE = 6;
  30184. Texture.EQUIRECTANGULAR_MODE = 7;
  30185. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30186. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30187. Texture.CLAMP_ADDRESSMODE = 0;
  30188. Texture.WRAP_ADDRESSMODE = 1;
  30189. Texture.MIRROR_ADDRESSMODE = 2;
  30190. /**
  30191. * 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
  30192. */
  30193. Texture.UseSerializedUrlIfAny = false;
  30194. __decorate([
  30195. BABYLON.serialize()
  30196. ], Texture.prototype, "url", void 0);
  30197. __decorate([
  30198. BABYLON.serialize()
  30199. ], Texture.prototype, "uOffset", void 0);
  30200. __decorate([
  30201. BABYLON.serialize()
  30202. ], Texture.prototype, "vOffset", void 0);
  30203. __decorate([
  30204. BABYLON.serialize()
  30205. ], Texture.prototype, "uScale", void 0);
  30206. __decorate([
  30207. BABYLON.serialize()
  30208. ], Texture.prototype, "vScale", void 0);
  30209. __decorate([
  30210. BABYLON.serialize()
  30211. ], Texture.prototype, "uAng", void 0);
  30212. __decorate([
  30213. BABYLON.serialize()
  30214. ], Texture.prototype, "vAng", void 0);
  30215. __decorate([
  30216. BABYLON.serialize()
  30217. ], Texture.prototype, "wAng", void 0);
  30218. __decorate([
  30219. BABYLON.serialize()
  30220. ], Texture.prototype, "isBlocking", null);
  30221. return Texture;
  30222. }(BABYLON.BaseTexture));
  30223. BABYLON.Texture = Texture;
  30224. })(BABYLON || (BABYLON = {}));
  30225. //# sourceMappingURL=babylon.texture.js.map
  30226. "use strict";
  30227. var BABYLON;
  30228. (function (BABYLON) {
  30229. var _InstancesBatch = /** @class */ (function () {
  30230. function _InstancesBatch() {
  30231. this.mustReturn = false;
  30232. this.visibleInstances = new Array();
  30233. this.renderSelf = new Array();
  30234. }
  30235. return _InstancesBatch;
  30236. }());
  30237. BABYLON._InstancesBatch = _InstancesBatch;
  30238. var Mesh = /** @class */ (function (_super) {
  30239. __extends(Mesh, _super);
  30240. /**
  30241. * @constructor
  30242. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30243. * @param {Scene} scene The scene to add this mesh to.
  30244. * @param {Node} parent The parent of this mesh, if it has one
  30245. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30246. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30247. * When false, achieved by calling a clone(), also passing False.
  30248. * This will make creation of children, recursive.
  30249. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30250. */
  30251. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30252. if (scene === void 0) { scene = null; }
  30253. if (parent === void 0) { parent = null; }
  30254. if (source === void 0) { source = null; }
  30255. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30256. var _this = _super.call(this, name, scene) || this;
  30257. // Events
  30258. /**
  30259. * An event triggered before rendering the mesh
  30260. */
  30261. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30262. /**
  30263. * An event triggered after rendering the mesh
  30264. */
  30265. _this.onAfterRenderObservable = new BABYLON.Observable();
  30266. /**
  30267. * An event triggered before drawing the mesh
  30268. */
  30269. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30270. // Members
  30271. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30272. _this.instances = new Array();
  30273. _this._LODLevels = new Array();
  30274. _this._visibleInstances = {};
  30275. _this._renderIdForInstances = new Array();
  30276. _this._batchCache = new _InstancesBatch();
  30277. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30278. // Use by builder only to know what orientation were the mesh build in.
  30279. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30280. _this.overrideMaterialSideOrientation = null;
  30281. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30282. // Will be used to save a source mesh reference, If any
  30283. _this._source = null;
  30284. scene = _this.getScene();
  30285. if (source) {
  30286. // Source mesh
  30287. _this._source = source;
  30288. // Geometry
  30289. if (source._geometry) {
  30290. source._geometry.applyToMesh(_this);
  30291. }
  30292. // Deep copy
  30293. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30294. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30295. // Metadata
  30296. if (source.metadata && source.metadata.clone) {
  30297. _this.metadata = source.metadata.clone();
  30298. }
  30299. else {
  30300. _this.metadata = source.metadata;
  30301. }
  30302. // Tags
  30303. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30304. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30305. }
  30306. // Parent
  30307. _this.parent = source.parent;
  30308. // Pivot
  30309. _this.setPivotMatrix(source.getPivotMatrix());
  30310. _this.id = name + "." + source.id;
  30311. // Material
  30312. _this.material = source.material;
  30313. var index;
  30314. if (!doNotCloneChildren) {
  30315. // Children
  30316. var directDescendants = source.getDescendants(true);
  30317. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30318. var child = directDescendants[index_1];
  30319. if (child.clone) {
  30320. child.clone(name + "." + child.name, _this);
  30321. }
  30322. }
  30323. }
  30324. // Physics clone
  30325. var physicsEngine = _this.getScene().getPhysicsEngine();
  30326. if (clonePhysicsImpostor && physicsEngine) {
  30327. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30328. if (impostor) {
  30329. _this.physicsImpostor = impostor.clone(_this);
  30330. }
  30331. }
  30332. // Particles
  30333. for (index = 0; index < scene.particleSystems.length; index++) {
  30334. var system = scene.particleSystems[index];
  30335. if (system.emitter === source) {
  30336. system.clone(system.name, _this);
  30337. }
  30338. }
  30339. _this.computeWorldMatrix(true);
  30340. }
  30341. // Parent
  30342. if (parent !== null) {
  30343. _this.parent = parent;
  30344. }
  30345. return _this;
  30346. }
  30347. Object.defineProperty(Mesh, "FRONTSIDE", {
  30348. /**
  30349. * Mesh side orientation : usually the external or front surface
  30350. */
  30351. get: function () {
  30352. return Mesh._FRONTSIDE;
  30353. },
  30354. enumerable: true,
  30355. configurable: true
  30356. });
  30357. Object.defineProperty(Mesh, "BACKSIDE", {
  30358. /**
  30359. * Mesh side orientation : usually the internal or back surface
  30360. */
  30361. get: function () {
  30362. return Mesh._BACKSIDE;
  30363. },
  30364. enumerable: true,
  30365. configurable: true
  30366. });
  30367. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30368. /**
  30369. * Mesh side orientation : both internal and external or front and back surfaces
  30370. */
  30371. get: function () {
  30372. return Mesh._DOUBLESIDE;
  30373. },
  30374. enumerable: true,
  30375. configurable: true
  30376. });
  30377. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30378. /**
  30379. * Mesh side orientation : by default, `FRONTSIDE`
  30380. */
  30381. get: function () {
  30382. return Mesh._DEFAULTSIDE;
  30383. },
  30384. enumerable: true,
  30385. configurable: true
  30386. });
  30387. Object.defineProperty(Mesh, "NO_CAP", {
  30388. /**
  30389. * Mesh cap setting : no cap
  30390. */
  30391. get: function () {
  30392. return Mesh._NO_CAP;
  30393. },
  30394. enumerable: true,
  30395. configurable: true
  30396. });
  30397. Object.defineProperty(Mesh, "CAP_START", {
  30398. /**
  30399. * Mesh cap setting : one cap at the beginning of the mesh
  30400. */
  30401. get: function () {
  30402. return Mesh._CAP_START;
  30403. },
  30404. enumerable: true,
  30405. configurable: true
  30406. });
  30407. Object.defineProperty(Mesh, "CAP_END", {
  30408. /**
  30409. * Mesh cap setting : one cap at the end of the mesh
  30410. */
  30411. get: function () {
  30412. return Mesh._CAP_END;
  30413. },
  30414. enumerable: true,
  30415. configurable: true
  30416. });
  30417. Object.defineProperty(Mesh, "CAP_ALL", {
  30418. /**
  30419. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30420. */
  30421. get: function () {
  30422. return Mesh._CAP_ALL;
  30423. },
  30424. enumerable: true,
  30425. configurable: true
  30426. });
  30427. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30428. set: function (callback) {
  30429. if (this._onBeforeDrawObserver) {
  30430. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30431. }
  30432. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30433. },
  30434. enumerable: true,
  30435. configurable: true
  30436. });
  30437. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30438. get: function () {
  30439. return this._morphTargetManager;
  30440. },
  30441. set: function (value) {
  30442. if (this._morphTargetManager === value) {
  30443. return;
  30444. }
  30445. this._morphTargetManager = value;
  30446. this._syncGeometryWithMorphTargetManager();
  30447. },
  30448. enumerable: true,
  30449. configurable: true
  30450. });
  30451. Object.defineProperty(Mesh.prototype, "source", {
  30452. get: function () {
  30453. return this._source;
  30454. },
  30455. enumerable: true,
  30456. configurable: true
  30457. });
  30458. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30459. get: function () {
  30460. return this._unIndexed;
  30461. },
  30462. set: function (value) {
  30463. if (this._unIndexed !== value) {
  30464. this._unIndexed = value;
  30465. this._markSubMeshesAsAttributesDirty();
  30466. }
  30467. },
  30468. enumerable: true,
  30469. configurable: true
  30470. });
  30471. // Methods
  30472. /**
  30473. * Returns the string "Mesh".
  30474. */
  30475. Mesh.prototype.getClassName = function () {
  30476. return "Mesh";
  30477. };
  30478. /**
  30479. * Returns a string.
  30480. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30481. */
  30482. Mesh.prototype.toString = function (fullDetails) {
  30483. var ret = _super.prototype.toString.call(this, fullDetails);
  30484. ret += ", n vertices: " + this.getTotalVertices();
  30485. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30486. if (this.animations) {
  30487. for (var i = 0; i < this.animations.length; i++) {
  30488. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30489. }
  30490. }
  30491. if (fullDetails) {
  30492. if (this._geometry) {
  30493. var ib = this.getIndices();
  30494. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30495. if (vb && ib) {
  30496. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30497. }
  30498. }
  30499. else {
  30500. ret += ", flat shading: UNKNOWN";
  30501. }
  30502. }
  30503. return ret;
  30504. };
  30505. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30506. /**
  30507. * True if the mesh has some Levels Of Details (LOD).
  30508. * Returns a boolean.
  30509. */
  30510. get: function () {
  30511. return this._LODLevels.length > 0;
  30512. },
  30513. enumerable: true,
  30514. configurable: true
  30515. });
  30516. /**
  30517. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30518. * @returns an array of {BABYLON.MeshLODLevel}
  30519. */
  30520. Mesh.prototype.getLODLevels = function () {
  30521. return this._LODLevels;
  30522. };
  30523. Mesh.prototype._sortLODLevels = function () {
  30524. this._LODLevels.sort(function (a, b) {
  30525. if (a.distance < b.distance) {
  30526. return 1;
  30527. }
  30528. if (a.distance > b.distance) {
  30529. return -1;
  30530. }
  30531. return 0;
  30532. });
  30533. };
  30534. /**
  30535. * Add a mesh as LOD level triggered at the given distance.
  30536. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30537. * @param {number} distance The distance from the center of the object to show this level
  30538. * @param {Mesh} mesh The mesh to be added as LOD level
  30539. * @return {Mesh} This mesh (for chaining)
  30540. */
  30541. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30542. if (mesh && mesh._masterMesh) {
  30543. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30544. return this;
  30545. }
  30546. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30547. this._LODLevels.push(level);
  30548. if (mesh) {
  30549. mesh._masterMesh = this;
  30550. }
  30551. this._sortLODLevels();
  30552. return this;
  30553. };
  30554. /**
  30555. * Returns the LOD level mesh at the passed distance or null if not found.
  30556. * It is related to the method `addLODLevel(distance, mesh)`.
  30557. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30558. * Returns an object Mesh or `null`.
  30559. */
  30560. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30561. for (var index = 0; index < this._LODLevels.length; index++) {
  30562. var level = this._LODLevels[index];
  30563. if (level.distance === distance) {
  30564. return level.mesh;
  30565. }
  30566. }
  30567. return null;
  30568. };
  30569. /**
  30570. * Remove a mesh from the LOD array
  30571. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30572. * @param {Mesh} mesh The mesh to be removed.
  30573. * @return {Mesh} This mesh (for chaining)
  30574. */
  30575. Mesh.prototype.removeLODLevel = function (mesh) {
  30576. for (var index = 0; index < this._LODLevels.length; index++) {
  30577. if (this._LODLevels[index].mesh === mesh) {
  30578. this._LODLevels.splice(index, 1);
  30579. if (mesh) {
  30580. mesh._masterMesh = null;
  30581. }
  30582. }
  30583. }
  30584. this._sortLODLevels();
  30585. return this;
  30586. };
  30587. /**
  30588. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30589. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30590. */
  30591. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30592. if (!this._LODLevels || this._LODLevels.length === 0) {
  30593. return this;
  30594. }
  30595. var bSphere;
  30596. if (boundingSphere) {
  30597. bSphere = boundingSphere;
  30598. }
  30599. else {
  30600. var boundingInfo = this.getBoundingInfo();
  30601. bSphere = boundingInfo.boundingSphere;
  30602. }
  30603. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30604. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30605. if (this.onLODLevelSelection) {
  30606. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30607. }
  30608. return this;
  30609. }
  30610. for (var index = 0; index < this._LODLevels.length; index++) {
  30611. var level = this._LODLevels[index];
  30612. if (level.distance < distanceToCamera) {
  30613. if (level.mesh) {
  30614. level.mesh._preActivate();
  30615. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30616. }
  30617. if (this.onLODLevelSelection) {
  30618. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30619. }
  30620. return level.mesh;
  30621. }
  30622. }
  30623. if (this.onLODLevelSelection) {
  30624. this.onLODLevelSelection(distanceToCamera, this, this);
  30625. }
  30626. return this;
  30627. };
  30628. Object.defineProperty(Mesh.prototype, "geometry", {
  30629. /**
  30630. * Returns the mesh internal Geometry object.
  30631. */
  30632. get: function () {
  30633. return this._geometry;
  30634. },
  30635. enumerable: true,
  30636. configurable: true
  30637. });
  30638. /**
  30639. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30640. */
  30641. Mesh.prototype.getTotalVertices = function () {
  30642. if (this._geometry === null || this._geometry === undefined) {
  30643. return 0;
  30644. }
  30645. return this._geometry.getTotalVertices();
  30646. };
  30647. /**
  30648. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30649. * 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.
  30650. * You can force the copy with forceCopy === true
  30651. * Returns null if the mesh has no geometry or no vertex buffer.
  30652. * Possible `kind` values :
  30653. * - BABYLON.VertexBuffer.PositionKind
  30654. * - BABYLON.VertexBuffer.UVKind
  30655. * - BABYLON.VertexBuffer.UV2Kind
  30656. * - BABYLON.VertexBuffer.UV3Kind
  30657. * - BABYLON.VertexBuffer.UV4Kind
  30658. * - BABYLON.VertexBuffer.UV5Kind
  30659. * - BABYLON.VertexBuffer.UV6Kind
  30660. * - BABYLON.VertexBuffer.ColorKind
  30661. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30662. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30663. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30664. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30665. */
  30666. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30667. if (!this._geometry) {
  30668. return null;
  30669. }
  30670. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30671. };
  30672. /**
  30673. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30674. * Returns `null` if the mesh has no geometry.
  30675. * Possible `kind` values :
  30676. * - BABYLON.VertexBuffer.PositionKind
  30677. * - BABYLON.VertexBuffer.UVKind
  30678. * - BABYLON.VertexBuffer.UV2Kind
  30679. * - BABYLON.VertexBuffer.UV3Kind
  30680. * - BABYLON.VertexBuffer.UV4Kind
  30681. * - BABYLON.VertexBuffer.UV5Kind
  30682. * - BABYLON.VertexBuffer.UV6Kind
  30683. * - BABYLON.VertexBuffer.ColorKind
  30684. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30685. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30686. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30687. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30688. */
  30689. Mesh.prototype.getVertexBuffer = function (kind) {
  30690. if (!this._geometry) {
  30691. return null;
  30692. }
  30693. return this._geometry.getVertexBuffer(kind);
  30694. };
  30695. /**
  30696. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  30697. * Possible `kind` values :
  30698. * - BABYLON.VertexBuffer.PositionKind
  30699. * - BABYLON.VertexBuffer.UVKind
  30700. * - BABYLON.VertexBuffer.UV2Kind
  30701. * - BABYLON.VertexBuffer.UV3Kind
  30702. * - BABYLON.VertexBuffer.UV4Kind
  30703. * - BABYLON.VertexBuffer.UV5Kind
  30704. * - BABYLON.VertexBuffer.UV6Kind
  30705. * - BABYLON.VertexBuffer.ColorKind
  30706. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30707. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30708. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30709. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30710. */
  30711. Mesh.prototype.isVerticesDataPresent = function (kind) {
  30712. if (!this._geometry) {
  30713. if (this._delayInfo) {
  30714. return this._delayInfo.indexOf(kind) !== -1;
  30715. }
  30716. return false;
  30717. }
  30718. return this._geometry.isVerticesDataPresent(kind);
  30719. };
  30720. /**
  30721. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30722. * Possible `kind` values :
  30723. * - BABYLON.VertexBuffer.PositionKind
  30724. * - BABYLON.VertexBuffer.UVKind
  30725. * - BABYLON.VertexBuffer.UV2Kind
  30726. * - BABYLON.VertexBuffer.UV3Kind
  30727. * - BABYLON.VertexBuffer.UV4Kind
  30728. * - BABYLON.VertexBuffer.UV5Kind
  30729. * - BABYLON.VertexBuffer.UV6Kind
  30730. * - BABYLON.VertexBuffer.ColorKind
  30731. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30732. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30733. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30734. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30735. */
  30736. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  30737. if (!this._geometry) {
  30738. if (this._delayInfo) {
  30739. return this._delayInfo.indexOf(kind) !== -1;
  30740. }
  30741. return false;
  30742. }
  30743. return this._geometry.isVertexBufferUpdatable(kind);
  30744. };
  30745. /**
  30746. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  30747. * Possible `kind` values :
  30748. * - BABYLON.VertexBuffer.PositionKind
  30749. * - BABYLON.VertexBuffer.UVKind
  30750. * - BABYLON.VertexBuffer.UV2Kind
  30751. * - BABYLON.VertexBuffer.UV3Kind
  30752. * - BABYLON.VertexBuffer.UV4Kind
  30753. * - BABYLON.VertexBuffer.UV5Kind
  30754. * - BABYLON.VertexBuffer.UV6Kind
  30755. * - BABYLON.VertexBuffer.ColorKind
  30756. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30757. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30758. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30759. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30760. */
  30761. Mesh.prototype.getVerticesDataKinds = function () {
  30762. if (!this._geometry) {
  30763. var result = new Array();
  30764. if (this._delayInfo) {
  30765. this._delayInfo.forEach(function (kind, index, array) {
  30766. result.push(kind);
  30767. });
  30768. }
  30769. return result;
  30770. }
  30771. return this._geometry.getVerticesDataKinds();
  30772. };
  30773. /**
  30774. * Returns a positive integer : the total number of indices in this mesh geometry.
  30775. * Returns zero if the mesh has no geometry.
  30776. */
  30777. Mesh.prototype.getTotalIndices = function () {
  30778. if (!this._geometry) {
  30779. return 0;
  30780. }
  30781. return this._geometry.getTotalIndices();
  30782. };
  30783. /**
  30784. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  30785. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  30786. * Returns an empty array if the mesh has no geometry.
  30787. */
  30788. Mesh.prototype.getIndices = function (copyWhenShared) {
  30789. if (!this._geometry) {
  30790. return [];
  30791. }
  30792. return this._geometry.getIndices(copyWhenShared);
  30793. };
  30794. Object.defineProperty(Mesh.prototype, "isBlocked", {
  30795. get: function () {
  30796. return this._masterMesh !== null && this._masterMesh !== undefined;
  30797. },
  30798. enumerable: true,
  30799. configurable: true
  30800. });
  30801. /**
  30802. * Determine if the current mesh is ready to be rendered
  30803. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  30804. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  30805. * @returns true if all associated assets are ready (material, textures, shaders)
  30806. */
  30807. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  30808. if (completeCheck === void 0) { completeCheck = false; }
  30809. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  30810. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30811. return false;
  30812. }
  30813. if (!_super.prototype.isReady.call(this, completeCheck)) {
  30814. return false;
  30815. }
  30816. if (!this.subMeshes || this.subMeshes.length === 0) {
  30817. return true;
  30818. }
  30819. if (!completeCheck) {
  30820. return true;
  30821. }
  30822. var engine = this.getEngine();
  30823. var scene = this.getScene();
  30824. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  30825. this.computeWorldMatrix();
  30826. var mat = this.material || scene.defaultMaterial;
  30827. if (mat) {
  30828. if (mat.storeEffectOnSubMeshes) {
  30829. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  30830. var subMesh = _a[_i];
  30831. var effectiveMaterial = subMesh.getMaterial();
  30832. if (effectiveMaterial) {
  30833. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  30834. return false;
  30835. }
  30836. }
  30837. }
  30838. }
  30839. else {
  30840. if (!mat.isReady(this, hardwareInstancedRendering)) {
  30841. return false;
  30842. }
  30843. }
  30844. }
  30845. // Shadows
  30846. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  30847. var light = _c[_b];
  30848. var generator = light.getShadowGenerator();
  30849. if (generator) {
  30850. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  30851. var subMesh = _e[_d];
  30852. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  30853. return false;
  30854. }
  30855. }
  30856. }
  30857. }
  30858. // LOD
  30859. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  30860. var lod = _g[_f];
  30861. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  30862. return false;
  30863. }
  30864. }
  30865. return true;
  30866. };
  30867. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  30868. /**
  30869. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  30870. * This property is pertinent only for updatable parametric shapes.
  30871. */
  30872. get: function () {
  30873. return this._areNormalsFrozen;
  30874. },
  30875. enumerable: true,
  30876. configurable: true
  30877. });
  30878. /**
  30879. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30880. * It has no effect at all on other shapes.
  30881. * It prevents the mesh normals from being recomputed on next `positions` array update.
  30882. * Returns the Mesh.
  30883. */
  30884. Mesh.prototype.freezeNormals = function () {
  30885. this._areNormalsFrozen = true;
  30886. return this;
  30887. };
  30888. /**
  30889. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30890. * It has no effect at all on other shapes.
  30891. * It reactivates the mesh normals computation if it was previously frozen.
  30892. * Returns the Mesh.
  30893. */
  30894. Mesh.prototype.unfreezeNormals = function () {
  30895. this._areNormalsFrozen = false;
  30896. return this;
  30897. };
  30898. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  30899. /**
  30900. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  30901. */
  30902. set: function (count) {
  30903. this._overridenInstanceCount = count;
  30904. },
  30905. enumerable: true,
  30906. configurable: true
  30907. });
  30908. // Methods
  30909. Mesh.prototype._preActivate = function () {
  30910. var sceneRenderId = this.getScene().getRenderId();
  30911. if (this._preActivateId === sceneRenderId) {
  30912. return this;
  30913. }
  30914. this._preActivateId = sceneRenderId;
  30915. this._visibleInstances = null;
  30916. return this;
  30917. };
  30918. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  30919. if (this._visibleInstances) {
  30920. this._visibleInstances.intermediateDefaultRenderId = renderId;
  30921. }
  30922. return this;
  30923. };
  30924. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  30925. if (!this._visibleInstances) {
  30926. this._visibleInstances = {};
  30927. this._visibleInstances.defaultRenderId = renderId;
  30928. this._visibleInstances.selfDefaultRenderId = this._renderId;
  30929. }
  30930. if (!this._visibleInstances[renderId]) {
  30931. this._visibleInstances[renderId] = new Array();
  30932. }
  30933. this._visibleInstances[renderId].push(instance);
  30934. return this;
  30935. };
  30936. /**
  30937. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  30938. * This means the mesh underlying bounding box and sphere are recomputed.
  30939. * Returns the Mesh.
  30940. */
  30941. Mesh.prototype.refreshBoundingInfo = function () {
  30942. return this._refreshBoundingInfo(false);
  30943. };
  30944. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  30945. if (this._boundingInfo && this._boundingInfo.isLocked) {
  30946. return this;
  30947. }
  30948. var data = this._getPositionData(applySkeleton);
  30949. if (data) {
  30950. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  30951. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30952. }
  30953. if (this.subMeshes) {
  30954. for (var index = 0; index < this.subMeshes.length; index++) {
  30955. this.subMeshes[index].refreshBoundingInfo();
  30956. }
  30957. }
  30958. this._updateBoundingInfo();
  30959. return this;
  30960. };
  30961. Mesh.prototype._getPositionData = function (applySkeleton) {
  30962. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30963. if (data && applySkeleton && this.skeleton) {
  30964. data = BABYLON.Tools.Slice(data);
  30965. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30966. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30967. if (matricesWeightsData && matricesIndicesData) {
  30968. var needExtras = this.numBoneInfluencers > 4;
  30969. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30970. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30971. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  30972. var tempVector = BABYLON.Tmp.Vector3[0];
  30973. var finalMatrix = BABYLON.Tmp.Matrix[0];
  30974. var tempMatrix = BABYLON.Tmp.Matrix[1];
  30975. var matWeightIdx = 0;
  30976. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  30977. finalMatrix.reset();
  30978. var inf;
  30979. var weight;
  30980. for (inf = 0; inf < 4; inf++) {
  30981. weight = matricesWeightsData[matWeightIdx + inf];
  30982. if (weight <= 0)
  30983. break;
  30984. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30985. finalMatrix.addToSelf(tempMatrix);
  30986. }
  30987. if (needExtras) {
  30988. for (inf = 0; inf < 4; inf++) {
  30989. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30990. if (weight <= 0)
  30991. break;
  30992. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30993. finalMatrix.addToSelf(tempMatrix);
  30994. }
  30995. }
  30996. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  30997. tempVector.toArray(data, index);
  30998. }
  30999. }
  31000. }
  31001. return data;
  31002. };
  31003. Mesh.prototype._createGlobalSubMesh = function (force) {
  31004. var totalVertices = this.getTotalVertices();
  31005. if (!totalVertices || !this.getIndices()) {
  31006. return null;
  31007. }
  31008. // Check if we need to recreate the submeshes
  31009. if (this.subMeshes && this.subMeshes.length > 0) {
  31010. var ib = this.getIndices();
  31011. if (!ib) {
  31012. return null;
  31013. }
  31014. var totalIndices = ib.length;
  31015. var needToRecreate = false;
  31016. if (force) {
  31017. needToRecreate = true;
  31018. }
  31019. else {
  31020. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31021. var submesh = _a[_i];
  31022. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31023. needToRecreate = true;
  31024. break;
  31025. }
  31026. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31027. needToRecreate = true;
  31028. break;
  31029. }
  31030. }
  31031. }
  31032. if (!needToRecreate) {
  31033. return this.subMeshes[0];
  31034. }
  31035. }
  31036. this.releaseSubMeshes();
  31037. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31038. };
  31039. Mesh.prototype.subdivide = function (count) {
  31040. if (count < 1) {
  31041. return;
  31042. }
  31043. var totalIndices = this.getTotalIndices();
  31044. var subdivisionSize = (totalIndices / count) | 0;
  31045. var offset = 0;
  31046. // Ensure that subdivisionSize is a multiple of 3
  31047. while (subdivisionSize % 3 !== 0) {
  31048. subdivisionSize++;
  31049. }
  31050. this.releaseSubMeshes();
  31051. for (var index = 0; index < count; index++) {
  31052. if (offset >= totalIndices) {
  31053. break;
  31054. }
  31055. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31056. offset += subdivisionSize;
  31057. }
  31058. this.synchronizeInstances();
  31059. };
  31060. /**
  31061. * Sets the vertex data of the mesh geometry for the requested `kind`.
  31062. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  31063. * The `data` are either a numeric array either a Float32Array.
  31064. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  31065. * 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).
  31066. * Note that a new underlying VertexBuffer object is created each call.
  31067. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  31068. *
  31069. * Possible `kind` values :
  31070. * - BABYLON.VertexBuffer.PositionKind
  31071. * - BABYLON.VertexBuffer.UVKind
  31072. * - BABYLON.VertexBuffer.UV2Kind
  31073. * - BABYLON.VertexBuffer.UV3Kind
  31074. * - BABYLON.VertexBuffer.UV4Kind
  31075. * - BABYLON.VertexBuffer.UV5Kind
  31076. * - BABYLON.VertexBuffer.UV6Kind
  31077. * - BABYLON.VertexBuffer.ColorKind
  31078. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31079. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31080. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31081. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31082. *
  31083. * Returns the Mesh.
  31084. */
  31085. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31086. if (updatable === void 0) { updatable = false; }
  31087. if (!this._geometry) {
  31088. var vertexData = new BABYLON.VertexData();
  31089. vertexData.set(data, kind);
  31090. var scene = this.getScene();
  31091. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31092. }
  31093. else {
  31094. this._geometry.setVerticesData(kind, data, updatable, stride);
  31095. }
  31096. return this;
  31097. };
  31098. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31099. if (updatable === void 0) { updatable = true; }
  31100. var vb = this.getVertexBuffer(kind);
  31101. if (!vb || vb.isUpdatable() === updatable) {
  31102. return;
  31103. }
  31104. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31105. };
  31106. /**
  31107. * Sets the mesh VertexBuffer.
  31108. * Returns the Mesh.
  31109. */
  31110. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31111. if (!this._geometry) {
  31112. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31113. }
  31114. this._geometry.setVerticesBuffer(buffer);
  31115. return this;
  31116. };
  31117. /**
  31118. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  31119. * If the mesh has no geometry, it is simply returned as it is.
  31120. * The `data` are either a numeric array either a Float32Array.
  31121. * No new underlying VertexBuffer object is created.
  31122. * 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.
  31123. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  31124. *
  31125. * Possible `kind` values :
  31126. * - BABYLON.VertexBuffer.PositionKind
  31127. * - BABYLON.VertexBuffer.UVKind
  31128. * - BABYLON.VertexBuffer.UV2Kind
  31129. * - BABYLON.VertexBuffer.UV3Kind
  31130. * - BABYLON.VertexBuffer.UV4Kind
  31131. * - BABYLON.VertexBuffer.UV5Kind
  31132. * - BABYLON.VertexBuffer.UV6Kind
  31133. * - BABYLON.VertexBuffer.ColorKind
  31134. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31135. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31136. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31137. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31138. *
  31139. * Returns the Mesh.
  31140. */
  31141. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31142. if (!this._geometry) {
  31143. return this;
  31144. }
  31145. if (!makeItUnique) {
  31146. this._geometry.updateVerticesData(kind, data, updateExtends);
  31147. }
  31148. else {
  31149. this.makeGeometryUnique();
  31150. this.updateVerticesData(kind, data, updateExtends, false);
  31151. }
  31152. return this;
  31153. };
  31154. /**
  31155. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31156. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31157. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31158. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31159. * Returns the Mesh.
  31160. */
  31161. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31162. if (computeNormals === void 0) { computeNormals = true; }
  31163. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31164. if (!positions) {
  31165. return this;
  31166. }
  31167. positionFunction(positions);
  31168. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31169. if (computeNormals) {
  31170. var indices = this.getIndices();
  31171. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31172. if (!normals) {
  31173. return this;
  31174. }
  31175. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31176. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31177. }
  31178. return this;
  31179. };
  31180. /**
  31181. * Creates a un-shared specific occurence of the geometry for the mesh.
  31182. * Returns the Mesh.
  31183. */
  31184. Mesh.prototype.makeGeometryUnique = function () {
  31185. if (!this._geometry) {
  31186. return this;
  31187. }
  31188. var oldGeometry = this._geometry;
  31189. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31190. oldGeometry.releaseForMesh(this, true);
  31191. geometry.applyToMesh(this);
  31192. return this;
  31193. };
  31194. /**
  31195. * Sets the mesh indices.
  31196. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  31197. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  31198. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  31199. * This method creates a new index buffer each call.
  31200. * Returns the Mesh.
  31201. */
  31202. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31203. if (totalVertices === void 0) { totalVertices = null; }
  31204. if (updatable === void 0) { updatable = false; }
  31205. if (!this._geometry) {
  31206. var vertexData = new BABYLON.VertexData();
  31207. vertexData.indices = indices;
  31208. var scene = this.getScene();
  31209. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31210. }
  31211. else {
  31212. this._geometry.setIndices(indices, totalVertices, updatable);
  31213. }
  31214. return this;
  31215. };
  31216. /**
  31217. * Update the current index buffer
  31218. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31219. * Returns the Mesh.
  31220. */
  31221. Mesh.prototype.updateIndices = function (indices, offset) {
  31222. if (!this._geometry) {
  31223. return this;
  31224. }
  31225. this._geometry.updateIndices(indices, offset);
  31226. return this;
  31227. };
  31228. /**
  31229. * Invert the geometry to move from a right handed system to a left handed one.
  31230. * Returns the Mesh.
  31231. */
  31232. Mesh.prototype.toLeftHanded = function () {
  31233. if (!this._geometry) {
  31234. return this;
  31235. }
  31236. this._geometry.toLeftHanded();
  31237. return this;
  31238. };
  31239. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31240. if (!this._geometry) {
  31241. return this;
  31242. }
  31243. var engine = this.getScene().getEngine();
  31244. // Wireframe
  31245. var indexToBind;
  31246. if (this._unIndexed) {
  31247. indexToBind = null;
  31248. }
  31249. else {
  31250. switch (fillMode) {
  31251. case BABYLON.Material.PointFillMode:
  31252. indexToBind = null;
  31253. break;
  31254. case BABYLON.Material.WireFrameFillMode:
  31255. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31256. break;
  31257. default:
  31258. case BABYLON.Material.TriangleFillMode:
  31259. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31260. break;
  31261. }
  31262. }
  31263. // VBOs
  31264. this._geometry._bind(effect, indexToBind);
  31265. return this;
  31266. };
  31267. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31268. if (alternate === void 0) { alternate = false; }
  31269. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31270. return this;
  31271. }
  31272. this.onBeforeDrawObservable.notifyObservers(this);
  31273. var scene = this.getScene();
  31274. var engine = scene.getEngine();
  31275. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31276. // or triangles as points
  31277. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31278. }
  31279. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31280. // Triangles as wireframe
  31281. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31282. }
  31283. else {
  31284. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31285. }
  31286. if (scene._isAlternateRenderingEnabled && !alternate) {
  31287. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31288. if (!effect || !scene.activeCamera) {
  31289. return this;
  31290. }
  31291. scene._switchToAlternateCameraConfiguration(true);
  31292. this._effectiveMaterial.bindView(effect);
  31293. this._effectiveMaterial.bindViewProjection(effect);
  31294. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31295. this._draw(subMesh, fillMode, instancesCount, true);
  31296. engine.setViewport(scene.activeCamera.viewport);
  31297. scene._switchToAlternateCameraConfiguration(false);
  31298. this._effectiveMaterial.bindView(effect);
  31299. this._effectiveMaterial.bindViewProjection(effect);
  31300. }
  31301. return this;
  31302. };
  31303. /**
  31304. * Registers for this mesh a javascript function called just before the rendering process.
  31305. * This function is passed the current mesh.
  31306. * Return the Mesh.
  31307. */
  31308. Mesh.prototype.registerBeforeRender = function (func) {
  31309. this.onBeforeRenderObservable.add(func);
  31310. return this;
  31311. };
  31312. /**
  31313. * Disposes a previously registered javascript function called before the rendering.
  31314. * This function is passed the current mesh.
  31315. * Returns the Mesh.
  31316. */
  31317. Mesh.prototype.unregisterBeforeRender = function (func) {
  31318. this.onBeforeRenderObservable.removeCallback(func);
  31319. return this;
  31320. };
  31321. /**
  31322. * Registers for this mesh a javascript function called just after the rendering is complete.
  31323. * This function is passed the current mesh.
  31324. * Returns the Mesh.
  31325. */
  31326. Mesh.prototype.registerAfterRender = function (func) {
  31327. this.onAfterRenderObservable.add(func);
  31328. return this;
  31329. };
  31330. /**
  31331. * Disposes a previously registered javascript function called after the rendering.
  31332. * This function is passed the current mesh.
  31333. * Return the Mesh.
  31334. */
  31335. Mesh.prototype.unregisterAfterRender = function (func) {
  31336. this.onAfterRenderObservable.removeCallback(func);
  31337. return this;
  31338. };
  31339. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31340. var scene = this.getScene();
  31341. this._batchCache.mustReturn = false;
  31342. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31343. this._batchCache.visibleInstances[subMeshId] = null;
  31344. if (this._visibleInstances) {
  31345. var currentRenderId = scene.getRenderId();
  31346. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31347. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31348. var selfRenderId = this._renderId;
  31349. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31350. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31351. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31352. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31353. }
  31354. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31355. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31356. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31357. this._batchCache.mustReturn = true;
  31358. return this._batchCache;
  31359. }
  31360. if (currentRenderId !== selfRenderId) {
  31361. this._batchCache.renderSelf[subMeshId] = false;
  31362. }
  31363. }
  31364. this._renderIdForInstances[subMeshId] = currentRenderId;
  31365. }
  31366. return this._batchCache;
  31367. };
  31368. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31369. var visibleInstances = batch.visibleInstances[subMesh._id];
  31370. if (!visibleInstances) {
  31371. return this;
  31372. }
  31373. var matricesCount = visibleInstances.length + 1;
  31374. var bufferSize = matricesCount * 16 * 4;
  31375. var currentInstancesBufferSize = this._instancesBufferSize;
  31376. var instancesBuffer = this._instancesBuffer;
  31377. while (this._instancesBufferSize < bufferSize) {
  31378. this._instancesBufferSize *= 2;
  31379. }
  31380. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31381. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31382. }
  31383. var offset = 0;
  31384. var instancesCount = 0;
  31385. var world = this.getWorldMatrix();
  31386. if (batch.renderSelf[subMesh._id]) {
  31387. world.copyToArray(this._instancesData, offset);
  31388. offset += 16;
  31389. instancesCount++;
  31390. }
  31391. if (visibleInstances) {
  31392. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31393. var instance = visibleInstances[instanceIndex];
  31394. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31395. offset += 16;
  31396. instancesCount++;
  31397. }
  31398. }
  31399. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31400. if (instancesBuffer) {
  31401. instancesBuffer.dispose();
  31402. }
  31403. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31404. this._instancesBuffer = instancesBuffer;
  31405. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31406. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31407. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31408. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31409. }
  31410. else {
  31411. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31412. }
  31413. this._bind(subMesh, effect, fillMode);
  31414. this._draw(subMesh, fillMode, instancesCount);
  31415. engine.unbindInstanceAttributes();
  31416. return this;
  31417. };
  31418. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31419. var scene = this.getScene();
  31420. var engine = scene.getEngine();
  31421. if (hardwareInstancedRendering) {
  31422. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31423. }
  31424. else {
  31425. if (batch.renderSelf[subMesh._id]) {
  31426. // Draw
  31427. if (onBeforeDraw) {
  31428. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31429. }
  31430. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31431. }
  31432. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31433. if (visibleInstancesForSubMesh) {
  31434. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31435. var instance = visibleInstancesForSubMesh[instanceIndex];
  31436. // World
  31437. var world = instance.getWorldMatrix();
  31438. if (onBeforeDraw) {
  31439. onBeforeDraw(true, world, effectiveMaterial);
  31440. }
  31441. // Draw
  31442. this._draw(subMesh, fillMode);
  31443. }
  31444. }
  31445. }
  31446. return this;
  31447. };
  31448. /**
  31449. * Triggers the draw call for the mesh.
  31450. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31451. * Returns the Mesh.
  31452. */
  31453. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31454. this.checkOcclusionQuery();
  31455. if (this._isOccluded) {
  31456. return this;
  31457. }
  31458. var scene = this.getScene();
  31459. // Managing instances
  31460. var batch = this._getInstancesRenderList(subMesh._id);
  31461. if (batch.mustReturn) {
  31462. return this;
  31463. }
  31464. // Checking geometry state
  31465. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31466. return this;
  31467. }
  31468. this.onBeforeRenderObservable.notifyObservers(this);
  31469. var engine = scene.getEngine();
  31470. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31471. // Material
  31472. var material = subMesh.getMaterial();
  31473. if (!material) {
  31474. return this;
  31475. }
  31476. this._effectiveMaterial = material;
  31477. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31478. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31479. return this;
  31480. }
  31481. }
  31482. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31483. return this;
  31484. }
  31485. // Alpha mode
  31486. if (enableAlphaMode) {
  31487. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31488. }
  31489. // Outline - step 1
  31490. var savedDepthWrite = engine.getDepthWrite();
  31491. if (this.renderOutline) {
  31492. engine.setDepthWrite(false);
  31493. scene.getOutlineRenderer().render(subMesh, batch);
  31494. engine.setDepthWrite(savedDepthWrite);
  31495. }
  31496. var effect;
  31497. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31498. effect = subMesh.effect;
  31499. }
  31500. else {
  31501. effect = this._effectiveMaterial.getEffect();
  31502. }
  31503. if (!effect) {
  31504. return this;
  31505. }
  31506. var sideOrientation = this.overrideMaterialSideOrientation;
  31507. if (sideOrientation == null) {
  31508. sideOrientation = this._effectiveMaterial.sideOrientation;
  31509. if (this._getWorldMatrixDeterminant() < 0) {
  31510. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31511. }
  31512. }
  31513. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31514. if (this._effectiveMaterial.forceDepthWrite) {
  31515. engine.setDepthWrite(true);
  31516. }
  31517. // Bind
  31518. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31519. if (!hardwareInstancedRendering) {
  31520. this._bind(subMesh, effect, fillMode);
  31521. }
  31522. var world = this.getWorldMatrix();
  31523. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31524. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31525. }
  31526. else {
  31527. this._effectiveMaterial.bind(world, this);
  31528. }
  31529. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31530. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31531. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31532. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31533. }
  31534. // Draw
  31535. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31536. // Unbind
  31537. this._effectiveMaterial.unbind();
  31538. // Outline - step 2
  31539. if (this.renderOutline && savedDepthWrite) {
  31540. engine.setDepthWrite(true);
  31541. engine.setColorWrite(false);
  31542. scene.getOutlineRenderer().render(subMesh, batch);
  31543. engine.setColorWrite(true);
  31544. }
  31545. // Overlay
  31546. if (this.renderOverlay) {
  31547. var currentMode = engine.getAlphaMode();
  31548. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31549. scene.getOutlineRenderer().render(subMesh, batch, true);
  31550. engine.setAlphaMode(currentMode);
  31551. }
  31552. this.onAfterRenderObservable.notifyObservers(this);
  31553. return this;
  31554. };
  31555. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31556. if (isInstance && effectiveMaterial) {
  31557. effectiveMaterial.bindOnlyWorldMatrix(world);
  31558. }
  31559. };
  31560. /**
  31561. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31562. */
  31563. Mesh.prototype.getEmittedParticleSystems = function () {
  31564. var results = new Array();
  31565. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31566. var particleSystem = this.getScene().particleSystems[index];
  31567. if (particleSystem.emitter === this) {
  31568. results.push(particleSystem);
  31569. }
  31570. }
  31571. return results;
  31572. };
  31573. /**
  31574. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31575. */
  31576. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31577. var results = new Array();
  31578. var descendants = this.getDescendants();
  31579. descendants.push(this);
  31580. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31581. var particleSystem = this.getScene().particleSystems[index];
  31582. var emitter = particleSystem.emitter;
  31583. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31584. results.push(particleSystem);
  31585. }
  31586. }
  31587. return results;
  31588. };
  31589. Mesh.prototype._checkDelayState = function () {
  31590. var scene = this.getScene();
  31591. if (this._geometry) {
  31592. this._geometry.load(scene);
  31593. }
  31594. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31595. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31596. this._queueLoad(scene);
  31597. }
  31598. return this;
  31599. };
  31600. Mesh.prototype._queueLoad = function (scene) {
  31601. var _this = this;
  31602. scene._addPendingData(this);
  31603. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31604. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31605. if (data instanceof ArrayBuffer) {
  31606. _this._delayLoadingFunction(data, _this);
  31607. }
  31608. else {
  31609. _this._delayLoadingFunction(JSON.parse(data), _this);
  31610. }
  31611. _this.instances.forEach(function (instance) {
  31612. instance._syncSubMeshes();
  31613. });
  31614. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31615. scene._removePendingData(_this);
  31616. }, function () { }, scene.database, getBinaryData);
  31617. return this;
  31618. };
  31619. /**
  31620. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31621. */
  31622. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31623. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31624. return false;
  31625. }
  31626. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31627. return false;
  31628. }
  31629. this._checkDelayState();
  31630. return true;
  31631. };
  31632. /**
  31633. * Sets the mesh material by the material or multiMaterial `id` property.
  31634. * The material `id` is a string identifying the material or the multiMaterial.
  31635. * This method returns the Mesh.
  31636. */
  31637. Mesh.prototype.setMaterialByID = function (id) {
  31638. var materials = this.getScene().materials;
  31639. var index;
  31640. for (index = materials.length - 1; index > -1; index--) {
  31641. if (materials[index].id === id) {
  31642. this.material = materials[index];
  31643. return this;
  31644. }
  31645. }
  31646. // Multi
  31647. var multiMaterials = this.getScene().multiMaterials;
  31648. for (index = multiMaterials.length - 1; index > -1; index--) {
  31649. if (multiMaterials[index].id === id) {
  31650. this.material = multiMaterials[index];
  31651. return this;
  31652. }
  31653. }
  31654. return this;
  31655. };
  31656. /**
  31657. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31658. */
  31659. Mesh.prototype.getAnimatables = function () {
  31660. var results = new Array();
  31661. if (this.material) {
  31662. results.push(this.material);
  31663. }
  31664. if (this.skeleton) {
  31665. results.push(this.skeleton);
  31666. }
  31667. return results;
  31668. };
  31669. /**
  31670. * Modifies the mesh geometry according to the passed transformation matrix.
  31671. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31672. * The mesh normals are modified accordingly the same transformation.
  31673. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  31674. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31675. * Returns the Mesh.
  31676. */
  31677. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31678. // Position
  31679. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31680. return this;
  31681. }
  31682. var submeshes = this.subMeshes.splice(0);
  31683. this._resetPointsArrayCache();
  31684. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31685. var temp = new Array();
  31686. var index;
  31687. for (index = 0; index < data.length; index += 3) {
  31688. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  31689. }
  31690. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  31691. // Normals
  31692. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31693. return this;
  31694. }
  31695. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31696. temp = [];
  31697. for (index = 0; index < data.length; index += 3) {
  31698. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  31699. }
  31700. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  31701. // flip faces?
  31702. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  31703. this.flipFaces();
  31704. }
  31705. // Restore submeshes
  31706. this.releaseSubMeshes();
  31707. this.subMeshes = submeshes;
  31708. return this;
  31709. };
  31710. /**
  31711. * Modifies the mesh geometry according to its own current World Matrix.
  31712. * The mesh World Matrix is then reset.
  31713. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  31714. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  31715. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31716. * Returns the Mesh.
  31717. */
  31718. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  31719. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  31720. this.scaling.copyFromFloats(1, 1, 1);
  31721. this.position.copyFromFloats(0, 0, 0);
  31722. this.rotation.copyFromFloats(0, 0, 0);
  31723. //only if quaternion is already set
  31724. if (this.rotationQuaternion) {
  31725. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  31726. }
  31727. this._worldMatrix = BABYLON.Matrix.Identity();
  31728. return this;
  31729. };
  31730. Object.defineProperty(Mesh.prototype, "_positions", {
  31731. // Cache
  31732. get: function () {
  31733. if (this._geometry) {
  31734. return this._geometry._positions;
  31735. }
  31736. return null;
  31737. },
  31738. enumerable: true,
  31739. configurable: true
  31740. });
  31741. Mesh.prototype._resetPointsArrayCache = function () {
  31742. if (this._geometry) {
  31743. this._geometry._resetPointsArrayCache();
  31744. }
  31745. return this;
  31746. };
  31747. Mesh.prototype._generatePointsArray = function () {
  31748. if (this._geometry) {
  31749. return this._geometry._generatePointsArray();
  31750. }
  31751. return false;
  31752. };
  31753. /**
  31754. * Returns a new Mesh object generated from the current mesh properties.
  31755. * This method must not get confused with createInstance().
  31756. * The parameter `name` is a string, the name given to the new mesh.
  31757. * The optional parameter `newParent` can be any Node object (default `null`).
  31758. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  31759. * 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.
  31760. */
  31761. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  31762. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31763. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  31764. };
  31765. /**
  31766. * Releases resources associated with this mesh.
  31767. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  31768. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  31769. */
  31770. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  31771. var _this = this;
  31772. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  31773. this.morphTargetManager = null;
  31774. if (this._geometry) {
  31775. this._geometry.releaseForMesh(this, true);
  31776. }
  31777. // Sources
  31778. var meshes = this.getScene().meshes;
  31779. meshes.forEach(function (abstractMesh) {
  31780. var mesh = abstractMesh;
  31781. if (mesh._source && mesh._source === _this) {
  31782. mesh._source = null;
  31783. }
  31784. });
  31785. this._source = null;
  31786. // Instances
  31787. if (this._instancesBuffer) {
  31788. this._instancesBuffer.dispose();
  31789. this._instancesBuffer = null;
  31790. }
  31791. while (this.instances.length) {
  31792. this.instances[0].dispose();
  31793. }
  31794. // Effect layers.
  31795. var effectLayers = this.getScene().effectLayers;
  31796. for (var i = 0; i < effectLayers.length; i++) {
  31797. var effectLayer = effectLayers[i];
  31798. if (effectLayer) {
  31799. effectLayer._disposeMesh(this);
  31800. }
  31801. }
  31802. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  31803. };
  31804. /**
  31805. * Modifies the mesh geometry according to a displacement map.
  31806. * 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.
  31807. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31808. * This method returns nothing.
  31809. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  31810. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31811. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  31812. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31813. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31814. *
  31815. * Returns the Mesh.
  31816. */
  31817. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  31818. var _this = this;
  31819. var scene = this.getScene();
  31820. var onload = function (img) {
  31821. // Getting height map data
  31822. var canvas = document.createElement("canvas");
  31823. var context = canvas.getContext("2d");
  31824. var heightMapWidth = img.width;
  31825. var heightMapHeight = img.height;
  31826. canvas.width = heightMapWidth;
  31827. canvas.height = heightMapHeight;
  31828. context.drawImage(img, 0, 0);
  31829. // Create VertexData from map data
  31830. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  31831. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  31832. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  31833. //execute success callback, if set
  31834. if (onSuccess) {
  31835. onSuccess(_this);
  31836. }
  31837. };
  31838. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  31839. return this;
  31840. };
  31841. /**
  31842. * Modifies the mesh geometry according to a displacementMap buffer.
  31843. * 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.
  31844. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31845. * This method returns nothing.
  31846. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  31847. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  31848. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31849. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31850. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31851. *
  31852. * Returns the Mesh.
  31853. */
  31854. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  31855. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  31856. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  31857. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31858. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  31859. return this;
  31860. }
  31861. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31862. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31863. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31864. var position = BABYLON.Vector3.Zero();
  31865. var normal = BABYLON.Vector3.Zero();
  31866. var uv = BABYLON.Vector2.Zero();
  31867. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  31868. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  31869. for (var index = 0; index < positions.length; index += 3) {
  31870. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  31871. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  31872. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  31873. // Compute height
  31874. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  31875. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  31876. var pos = (u + v * heightMapWidth) * 4;
  31877. var r = buffer[pos] / 255.0;
  31878. var g = buffer[pos + 1] / 255.0;
  31879. var b = buffer[pos + 2] / 255.0;
  31880. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31881. normal.normalize();
  31882. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  31883. position = position.add(normal);
  31884. position.toArray(positions, index);
  31885. }
  31886. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  31887. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  31888. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31889. return this;
  31890. };
  31891. /**
  31892. * Modify the mesh to get a flat shading rendering.
  31893. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  31894. * This method returns the Mesh.
  31895. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  31896. */
  31897. Mesh.prototype.convertToFlatShadedMesh = function () {
  31898. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  31899. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31900. var kinds = this.getVerticesDataKinds();
  31901. var vbs = {};
  31902. var data = {};
  31903. var newdata = {};
  31904. var updatableNormals = false;
  31905. var kindIndex;
  31906. var kind;
  31907. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31908. kind = kinds[kindIndex];
  31909. var vertexBuffer = this.getVertexBuffer(kind);
  31910. if (kind === BABYLON.VertexBuffer.NormalKind) {
  31911. updatableNormals = vertexBuffer.isUpdatable();
  31912. kinds.splice(kindIndex, 1);
  31913. kindIndex--;
  31914. continue;
  31915. }
  31916. vbs[kind] = vertexBuffer;
  31917. data[kind] = vbs[kind].getData();
  31918. newdata[kind] = [];
  31919. }
  31920. // Save previous submeshes
  31921. var previousSubmeshes = this.subMeshes.slice(0);
  31922. var indices = this.getIndices();
  31923. var totalIndices = this.getTotalIndices();
  31924. // Generating unique vertices per face
  31925. var index;
  31926. for (index = 0; index < totalIndices; index++) {
  31927. var vertexIndex = indices[index];
  31928. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31929. kind = kinds[kindIndex];
  31930. var stride = vbs[kind].getStrideSize();
  31931. for (var offset = 0; offset < stride; offset++) {
  31932. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  31933. }
  31934. }
  31935. }
  31936. // Updating faces & normal
  31937. var normals = [];
  31938. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  31939. for (index = 0; index < totalIndices; index += 3) {
  31940. indices[index] = index;
  31941. indices[index + 1] = index + 1;
  31942. indices[index + 2] = index + 2;
  31943. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  31944. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  31945. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  31946. var p1p2 = p1.subtract(p2);
  31947. var p3p2 = p3.subtract(p2);
  31948. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  31949. // Store same normals for every vertex
  31950. for (var localIndex = 0; localIndex < 3; localIndex++) {
  31951. normals.push(normal.x);
  31952. normals.push(normal.y);
  31953. normals.push(normal.z);
  31954. }
  31955. }
  31956. this.setIndices(indices);
  31957. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  31958. // Updating vertex buffers
  31959. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31960. kind = kinds[kindIndex];
  31961. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  31962. }
  31963. // Updating submeshes
  31964. this.releaseSubMeshes();
  31965. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  31966. var previousOne = previousSubmeshes[submeshIndex];
  31967. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  31968. }
  31969. this.synchronizeInstances();
  31970. return this;
  31971. };
  31972. /**
  31973. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  31974. * In other words, more vertices, no more indices and a single bigger VBO.
  31975. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  31976. * Returns the Mesh.
  31977. */
  31978. Mesh.prototype.convertToUnIndexedMesh = function () {
  31979. /// <summary>Remove indices by unfolding faces into buffers</summary>
  31980. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31981. var kinds = this.getVerticesDataKinds();
  31982. var vbs = {};
  31983. var data = {};
  31984. var newdata = {};
  31985. var kindIndex;
  31986. var kind;
  31987. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31988. kind = kinds[kindIndex];
  31989. var vertexBuffer = this.getVertexBuffer(kind);
  31990. vbs[kind] = vertexBuffer;
  31991. data[kind] = vbs[kind].getData();
  31992. newdata[kind] = [];
  31993. }
  31994. // Save previous submeshes
  31995. var previousSubmeshes = this.subMeshes.slice(0);
  31996. var indices = this.getIndices();
  31997. var totalIndices = this.getTotalIndices();
  31998. // Generating unique vertices per face
  31999. var index;
  32000. for (index = 0; index < totalIndices; index++) {
  32001. var vertexIndex = indices[index];
  32002. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32003. kind = kinds[kindIndex];
  32004. var stride = vbs[kind].getStrideSize();
  32005. for (var offset = 0; offset < stride; offset++) {
  32006. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32007. }
  32008. }
  32009. }
  32010. // Updating indices
  32011. for (index = 0; index < totalIndices; index += 3) {
  32012. indices[index] = index;
  32013. indices[index + 1] = index + 1;
  32014. indices[index + 2] = index + 2;
  32015. }
  32016. this.setIndices(indices);
  32017. // Updating vertex buffers
  32018. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32019. kind = kinds[kindIndex];
  32020. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32021. }
  32022. // Updating submeshes
  32023. this.releaseSubMeshes();
  32024. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32025. var previousOne = previousSubmeshes[submeshIndex];
  32026. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32027. }
  32028. this._unIndexed = true;
  32029. this.synchronizeInstances();
  32030. return this;
  32031. };
  32032. /**
  32033. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32034. * This method returns the Mesh.
  32035. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32036. */
  32037. Mesh.prototype.flipFaces = function (flipNormals) {
  32038. if (flipNormals === void 0) { flipNormals = false; }
  32039. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32040. var i;
  32041. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32042. for (i = 0; i < vertex_data.normals.length; i++) {
  32043. vertex_data.normals[i] *= -1;
  32044. }
  32045. }
  32046. if (vertex_data.indices) {
  32047. var temp;
  32048. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32049. // reassign indices
  32050. temp = vertex_data.indices[i + 1];
  32051. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32052. vertex_data.indices[i + 2] = temp;
  32053. }
  32054. }
  32055. vertex_data.applyToMesh(this);
  32056. return this;
  32057. };
  32058. // Instances
  32059. /**
  32060. * Creates a new InstancedMesh object from the mesh model.
  32061. * An instance shares the same properties and the same material than its model.
  32062. * Only these properties of each instance can then be set individually :
  32063. * - position
  32064. * - rotation
  32065. * - rotationQuaternion
  32066. * - setPivotMatrix
  32067. * - scaling
  32068. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32069. * Warning : this method is not supported for Line mesh and LineSystem
  32070. */
  32071. Mesh.prototype.createInstance = function (name) {
  32072. return new BABYLON.InstancedMesh(name, this);
  32073. };
  32074. /**
  32075. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32076. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32077. * This method returns the Mesh.
  32078. */
  32079. Mesh.prototype.synchronizeInstances = function () {
  32080. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32081. var instance = this.instances[instanceIndex];
  32082. instance._syncSubMeshes();
  32083. }
  32084. return this;
  32085. };
  32086. /**
  32087. * Simplify the mesh according to the given array of settings.
  32088. * Function will return immediately and will simplify async. It returns the Mesh.
  32089. * @param settings a collection of simplification settings.
  32090. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32091. * @param type the type of simplification to run.
  32092. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32093. */
  32094. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32095. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32096. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32097. this.getScene().simplificationQueue.addTask({
  32098. settings: settings,
  32099. parallelProcessing: parallelProcessing,
  32100. mesh: this,
  32101. simplificationType: simplificationType,
  32102. successCallback: successCallback
  32103. });
  32104. return this;
  32105. };
  32106. /**
  32107. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32108. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32109. * This should be used together with the simplification to avoid disappearing triangles.
  32110. * Returns the Mesh.
  32111. * @param successCallback an optional success callback to be called after the optimization finished.
  32112. */
  32113. Mesh.prototype.optimizeIndices = function (successCallback) {
  32114. var _this = this;
  32115. var indices = this.getIndices();
  32116. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32117. if (!positions || !indices) {
  32118. return this;
  32119. }
  32120. var vectorPositions = new Array();
  32121. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32122. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32123. }
  32124. var dupes = new Array();
  32125. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32126. var realPos = vectorPositions.length - 1 - iteration;
  32127. var testedPosition = vectorPositions[realPos];
  32128. for (var j = 0; j < realPos; ++j) {
  32129. var againstPosition = vectorPositions[j];
  32130. if (testedPosition.equals(againstPosition)) {
  32131. dupes[realPos] = j;
  32132. break;
  32133. }
  32134. }
  32135. }, function () {
  32136. for (var i = 0; i < indices.length; ++i) {
  32137. indices[i] = dupes[indices[i]] || indices[i];
  32138. }
  32139. //indices are now reordered
  32140. var originalSubMeshes = _this.subMeshes.slice(0);
  32141. _this.setIndices(indices);
  32142. _this.subMeshes = originalSubMeshes;
  32143. if (successCallback) {
  32144. successCallback(_this);
  32145. }
  32146. });
  32147. return this;
  32148. };
  32149. Mesh.prototype.serialize = function (serializationObject) {
  32150. serializationObject.name = this.name;
  32151. serializationObject.id = this.id;
  32152. serializationObject.type = this.getClassName();
  32153. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32154. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32155. }
  32156. serializationObject.position = this.position.asArray();
  32157. if (this.rotationQuaternion) {
  32158. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32159. }
  32160. else if (this.rotation) {
  32161. serializationObject.rotation = this.rotation.asArray();
  32162. }
  32163. serializationObject.scaling = this.scaling.asArray();
  32164. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32165. serializationObject.isEnabled = this.isEnabled(false);
  32166. serializationObject.isVisible = this.isVisible;
  32167. serializationObject.infiniteDistance = this.infiniteDistance;
  32168. serializationObject.pickable = this.isPickable;
  32169. serializationObject.receiveShadows = this.receiveShadows;
  32170. serializationObject.billboardMode = this.billboardMode;
  32171. serializationObject.visibility = this.visibility;
  32172. serializationObject.checkCollisions = this.checkCollisions;
  32173. serializationObject.isBlocker = this.isBlocker;
  32174. // Parent
  32175. if (this.parent) {
  32176. serializationObject.parentId = this.parent.id;
  32177. }
  32178. // Geometry
  32179. serializationObject.isUnIndexed = this.isUnIndexed;
  32180. var geometry = this._geometry;
  32181. if (geometry) {
  32182. var geometryId = geometry.id;
  32183. serializationObject.geometryId = geometryId;
  32184. // SubMeshes
  32185. serializationObject.subMeshes = [];
  32186. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32187. var subMesh = this.subMeshes[subIndex];
  32188. serializationObject.subMeshes.push({
  32189. materialIndex: subMesh.materialIndex,
  32190. verticesStart: subMesh.verticesStart,
  32191. verticesCount: subMesh.verticesCount,
  32192. indexStart: subMesh.indexStart,
  32193. indexCount: subMesh.indexCount
  32194. });
  32195. }
  32196. }
  32197. // Material
  32198. if (this.material) {
  32199. serializationObject.materialId = this.material.id;
  32200. }
  32201. else {
  32202. this.material = null;
  32203. }
  32204. // Morph targets
  32205. if (this.morphTargetManager) {
  32206. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32207. }
  32208. // Skeleton
  32209. if (this.skeleton) {
  32210. serializationObject.skeletonId = this.skeleton.id;
  32211. }
  32212. // Physics
  32213. //TODO implement correct serialization for physics impostors.
  32214. var impostor = this.getPhysicsImpostor();
  32215. if (impostor) {
  32216. serializationObject.physicsMass = impostor.getParam("mass");
  32217. serializationObject.physicsFriction = impostor.getParam("friction");
  32218. serializationObject.physicsRestitution = impostor.getParam("mass");
  32219. serializationObject.physicsImpostor = impostor.type;
  32220. }
  32221. // Metadata
  32222. if (this.metadata) {
  32223. serializationObject.metadata = this.metadata;
  32224. }
  32225. // Instances
  32226. serializationObject.instances = [];
  32227. for (var index = 0; index < this.instances.length; index++) {
  32228. var instance = this.instances[index];
  32229. var serializationInstance = {
  32230. name: instance.name,
  32231. id: instance.id,
  32232. position: instance.position.asArray(),
  32233. scaling: instance.scaling.asArray()
  32234. };
  32235. if (instance.rotationQuaternion) {
  32236. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32237. }
  32238. else if (instance.rotation) {
  32239. serializationInstance.rotation = instance.rotation.asArray();
  32240. }
  32241. serializationObject.instances.push(serializationInstance);
  32242. // Animations
  32243. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32244. serializationInstance.ranges = instance.serializeAnimationRanges();
  32245. }
  32246. //
  32247. // Animations
  32248. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32249. serializationObject.ranges = this.serializeAnimationRanges();
  32250. // Layer mask
  32251. serializationObject.layerMask = this.layerMask;
  32252. // Alpha
  32253. serializationObject.alphaIndex = this.alphaIndex;
  32254. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32255. // Overlay
  32256. serializationObject.overlayAlpha = this.overlayAlpha;
  32257. serializationObject.overlayColor = this.overlayColor.asArray();
  32258. serializationObject.renderOverlay = this.renderOverlay;
  32259. // Fog
  32260. serializationObject.applyFog = this.applyFog;
  32261. // Action Manager
  32262. if (this.actionManager) {
  32263. serializationObject.actions = this.actionManager.serialize(this.name);
  32264. }
  32265. };
  32266. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32267. if (!this.geometry) {
  32268. return;
  32269. }
  32270. this._markSubMeshesAsAttributesDirty();
  32271. var morphTargetManager = this._morphTargetManager;
  32272. if (morphTargetManager && morphTargetManager.vertexCount) {
  32273. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32274. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32275. this.morphTargetManager = null;
  32276. return;
  32277. }
  32278. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32279. var morphTarget = morphTargetManager.getActiveTarget(index);
  32280. var positions = morphTarget.getPositions();
  32281. if (!positions) {
  32282. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32283. return;
  32284. }
  32285. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32286. var normals = morphTarget.getNormals();
  32287. if (normals) {
  32288. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32289. }
  32290. var tangents = morphTarget.getTangents();
  32291. if (tangents) {
  32292. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32293. }
  32294. }
  32295. }
  32296. else {
  32297. var index = 0;
  32298. // Positions
  32299. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32300. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32301. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32302. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32303. }
  32304. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32305. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32306. }
  32307. index++;
  32308. }
  32309. }
  32310. };
  32311. // Statics
  32312. /**
  32313. * Returns a new Mesh object parsed from the source provided.
  32314. * The parameter `parsedMesh` is the source.
  32315. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32316. */
  32317. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32318. var mesh;
  32319. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32320. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32321. }
  32322. else {
  32323. mesh = new Mesh(parsedMesh.name, scene);
  32324. }
  32325. mesh.id = parsedMesh.id;
  32326. if (BABYLON.Tags) {
  32327. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32328. }
  32329. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32330. if (parsedMesh.metadata !== undefined) {
  32331. mesh.metadata = parsedMesh.metadata;
  32332. }
  32333. if (parsedMesh.rotationQuaternion) {
  32334. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32335. }
  32336. else if (parsedMesh.rotation) {
  32337. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32338. }
  32339. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32340. if (parsedMesh.localMatrix) {
  32341. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32342. }
  32343. else if (parsedMesh.pivotMatrix) {
  32344. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32345. }
  32346. mesh.setEnabled(parsedMesh.isEnabled);
  32347. mesh.isVisible = parsedMesh.isVisible;
  32348. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32349. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32350. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32351. if (parsedMesh.applyFog !== undefined) {
  32352. mesh.applyFog = parsedMesh.applyFog;
  32353. }
  32354. if (parsedMesh.pickable !== undefined) {
  32355. mesh.isPickable = parsedMesh.pickable;
  32356. }
  32357. if (parsedMesh.alphaIndex !== undefined) {
  32358. mesh.alphaIndex = parsedMesh.alphaIndex;
  32359. }
  32360. mesh.receiveShadows = parsedMesh.receiveShadows;
  32361. mesh.billboardMode = parsedMesh.billboardMode;
  32362. if (parsedMesh.visibility !== undefined) {
  32363. mesh.visibility = parsedMesh.visibility;
  32364. }
  32365. mesh.checkCollisions = parsedMesh.checkCollisions;
  32366. if (parsedMesh.isBlocker !== undefined) {
  32367. mesh.isBlocker = parsedMesh.isBlocker;
  32368. }
  32369. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32370. // freezeWorldMatrix
  32371. if (parsedMesh.freezeWorldMatrix) {
  32372. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32373. }
  32374. // Parent
  32375. if (parsedMesh.parentId) {
  32376. mesh._waitingParentId = parsedMesh.parentId;
  32377. }
  32378. // Actions
  32379. if (parsedMesh.actions !== undefined) {
  32380. mesh._waitingActions = parsedMesh.actions;
  32381. }
  32382. // Overlay
  32383. if (parsedMesh.overlayAlpha !== undefined) {
  32384. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32385. }
  32386. if (parsedMesh.overlayColor !== undefined) {
  32387. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32388. }
  32389. if (parsedMesh.renderOverlay !== undefined) {
  32390. mesh.renderOverlay = parsedMesh.renderOverlay;
  32391. }
  32392. // Geometry
  32393. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32394. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32395. if (parsedMesh.delayLoadingFile) {
  32396. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32397. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32398. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32399. if (parsedMesh._binaryInfo) {
  32400. mesh._binaryInfo = parsedMesh._binaryInfo;
  32401. }
  32402. mesh._delayInfo = [];
  32403. if (parsedMesh.hasUVs) {
  32404. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32405. }
  32406. if (parsedMesh.hasUVs2) {
  32407. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32408. }
  32409. if (parsedMesh.hasUVs3) {
  32410. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32411. }
  32412. if (parsedMesh.hasUVs4) {
  32413. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32414. }
  32415. if (parsedMesh.hasUVs5) {
  32416. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32417. }
  32418. if (parsedMesh.hasUVs6) {
  32419. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32420. }
  32421. if (parsedMesh.hasColors) {
  32422. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32423. }
  32424. if (parsedMesh.hasMatricesIndices) {
  32425. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32426. }
  32427. if (parsedMesh.hasMatricesWeights) {
  32428. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32429. }
  32430. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32431. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32432. mesh._checkDelayState();
  32433. }
  32434. }
  32435. else {
  32436. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32437. }
  32438. // Material
  32439. if (parsedMesh.materialId) {
  32440. mesh.setMaterialByID(parsedMesh.materialId);
  32441. }
  32442. else {
  32443. mesh.material = null;
  32444. }
  32445. // Morph targets
  32446. if (parsedMesh.morphTargetManagerId > -1) {
  32447. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32448. }
  32449. // Skeleton
  32450. if (parsedMesh.skeletonId > -1) {
  32451. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32452. if (parsedMesh.numBoneInfluencers) {
  32453. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32454. }
  32455. }
  32456. // Animations
  32457. if (parsedMesh.animations) {
  32458. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32459. var parsedAnimation = parsedMesh.animations[animationIndex];
  32460. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32461. }
  32462. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32463. }
  32464. if (parsedMesh.autoAnimate) {
  32465. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32466. }
  32467. // Layer Mask
  32468. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32469. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32470. }
  32471. else {
  32472. mesh.layerMask = 0x0FFFFFFF;
  32473. }
  32474. // Physics
  32475. if (parsedMesh.physicsImpostor) {
  32476. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32477. mass: parsedMesh.physicsMass,
  32478. friction: parsedMesh.physicsFriction,
  32479. restitution: parsedMesh.physicsRestitution
  32480. }, scene);
  32481. }
  32482. // Instances
  32483. if (parsedMesh.instances) {
  32484. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32485. var parsedInstance = parsedMesh.instances[index];
  32486. var instance = mesh.createInstance(parsedInstance.name);
  32487. if (parsedInstance.id) {
  32488. instance.id = parsedInstance.id;
  32489. }
  32490. if (BABYLON.Tags) {
  32491. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32492. }
  32493. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32494. if (parsedInstance.parentId) {
  32495. instance._waitingParentId = parsedInstance.parentId;
  32496. }
  32497. if (parsedInstance.rotationQuaternion) {
  32498. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32499. }
  32500. else if (parsedInstance.rotation) {
  32501. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32502. }
  32503. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32504. instance.checkCollisions = mesh.checkCollisions;
  32505. if (parsedMesh.animations) {
  32506. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32507. parsedAnimation = parsedMesh.animations[animationIndex];
  32508. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32509. }
  32510. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32511. }
  32512. }
  32513. }
  32514. return mesh;
  32515. };
  32516. /**
  32517. * Creates a ribbon mesh.
  32518. * Please consider using the same method from the MeshBuilder class instead.
  32519. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  32520. *
  32521. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32522. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32523. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32524. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32525. * 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.
  32526. * 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.
  32527. * 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
  32528. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32529. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32530. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32531. */
  32532. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32533. if (closeArray === void 0) { closeArray = false; }
  32534. if (updatable === void 0) { updatable = false; }
  32535. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32536. pathArray: pathArray,
  32537. closeArray: closeArray,
  32538. closePath: closePath,
  32539. offset: offset,
  32540. updatable: updatable,
  32541. sideOrientation: sideOrientation,
  32542. instance: instance
  32543. }, scene);
  32544. };
  32545. /**
  32546. * Creates a plane polygonal mesh. By default, this is a disc.
  32547. * Please consider using the same method from the MeshBuilder class instead.
  32548. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32549. * 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.
  32550. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32551. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32553. */
  32554. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32555. if (scene === void 0) { scene = null; }
  32556. var options = {
  32557. radius: radius,
  32558. tessellation: tessellation,
  32559. sideOrientation: sideOrientation,
  32560. updatable: updatable
  32561. };
  32562. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32563. };
  32564. /**
  32565. * Creates a box mesh.
  32566. * Please consider using the same method from the MeshBuilder class instead.
  32567. * The parameter `size` sets the size (float) of each box side (default 1).
  32568. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32569. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32571. */
  32572. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32573. if (scene === void 0) { scene = null; }
  32574. var options = {
  32575. size: size,
  32576. sideOrientation: sideOrientation,
  32577. updatable: updatable
  32578. };
  32579. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32580. };
  32581. /**
  32582. * Creates a sphere mesh.
  32583. * Please consider using the same method from the MeshBuilder class instead.
  32584. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32585. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32586. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32587. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32589. */
  32590. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32591. var options = {
  32592. segments: segments,
  32593. diameterX: diameter,
  32594. diameterY: diameter,
  32595. diameterZ: diameter,
  32596. sideOrientation: sideOrientation,
  32597. updatable: updatable
  32598. };
  32599. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32600. };
  32601. /**
  32602. * Creates a cylinder or a cone mesh.
  32603. * Please consider using the same method from the MeshBuilder class instead.
  32604. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32605. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32606. * 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.
  32607. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32608. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32609. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32610. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32611. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32612. */
  32613. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32614. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32615. if (scene !== undefined) {
  32616. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32617. updatable = scene;
  32618. }
  32619. scene = subdivisions;
  32620. subdivisions = 1;
  32621. }
  32622. var options = {
  32623. height: height,
  32624. diameterTop: diameterTop,
  32625. diameterBottom: diameterBottom,
  32626. tessellation: tessellation,
  32627. subdivisions: subdivisions,
  32628. sideOrientation: sideOrientation,
  32629. updatable: updatable
  32630. };
  32631. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32632. };
  32633. // Torus (Code from SharpDX.org)
  32634. /**
  32635. * Creates a torus mesh.
  32636. * Please consider using the same method from the MeshBuilder class instead.
  32637. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32638. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32639. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32640. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32641. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32642. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32643. */
  32644. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32645. var options = {
  32646. diameter: diameter,
  32647. thickness: thickness,
  32648. tessellation: tessellation,
  32649. sideOrientation: sideOrientation,
  32650. updatable: updatable
  32651. };
  32652. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32653. };
  32654. /**
  32655. * Creates a torus knot mesh.
  32656. * Please consider using the same method from the MeshBuilder class instead.
  32657. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32658. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32659. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32660. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32661. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32662. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32663. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32664. */
  32665. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32666. var options = {
  32667. radius: radius,
  32668. tube: tube,
  32669. radialSegments: radialSegments,
  32670. tubularSegments: tubularSegments,
  32671. p: p,
  32672. q: q,
  32673. sideOrientation: sideOrientation,
  32674. updatable: updatable
  32675. };
  32676. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  32677. };
  32678. /**
  32679. * Creates a line mesh.
  32680. * Please consider using the same method from the MeshBuilder class instead.
  32681. * 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.
  32682. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32683. * The parameter `points` is an array successive Vector3.
  32684. * 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
  32685. * When updating an instance, remember that only point positions can change, not the number of points.
  32686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32687. */
  32688. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  32689. if (scene === void 0) { scene = null; }
  32690. if (updatable === void 0) { updatable = false; }
  32691. if (instance === void 0) { instance = null; }
  32692. var options = {
  32693. points: points,
  32694. updatable: updatable,
  32695. instance: instance
  32696. };
  32697. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  32698. };
  32699. /**
  32700. * Creates a dashed line mesh.
  32701. * Please consider using the same method from the MeshBuilder class instead.
  32702. * 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.
  32703. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32704. * The parameter `points` is an array successive Vector3.
  32705. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  32706. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  32707. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  32708. * 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
  32709. * When updating an instance, remember that only point positions can change, not the number of points.
  32710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32711. */
  32712. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  32713. if (scene === void 0) { scene = null; }
  32714. var options = {
  32715. points: points,
  32716. dashSize: dashSize,
  32717. gapSize: gapSize,
  32718. dashNb: dashNb,
  32719. updatable: updatable,
  32720. instance: instance
  32721. };
  32722. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  32723. };
  32724. /**
  32725. * Creates a polygon mesh.
  32726. * Please consider using the same method from the MeshBuilder class instead.
  32727. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  32728. * 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.
  32729. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32730. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32731. * Remember you can only change the shape positions, not their number when updating a polygon.
  32732. */
  32733. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  32734. var options = {
  32735. shape: shape,
  32736. holes: holes,
  32737. updatable: updatable,
  32738. sideOrientation: sideOrientation
  32739. };
  32740. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  32741. };
  32742. /**
  32743. * Creates an extruded polygon mesh, with depth in the Y direction.
  32744. * Please consider using the same method from the MeshBuilder class instead.
  32745. */
  32746. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  32747. var options = {
  32748. shape: shape,
  32749. holes: holes,
  32750. depth: depth,
  32751. updatable: updatable,
  32752. sideOrientation: sideOrientation
  32753. };
  32754. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  32755. };
  32756. /**
  32757. * Creates an extruded shape mesh.
  32758. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  32759. * Please consider using the same method from the MeshBuilder class instead.
  32760. *
  32761. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32762. * 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
  32763. * extruded along the Z axis.
  32764. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32765. * 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.
  32766. * The parameter `scale` (float, default 1) is the value to scale the shape.
  32767. * 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
  32768. * 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
  32769. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32770. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32771. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32772. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32773. */
  32774. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  32775. if (scene === void 0) { scene = null; }
  32776. var options = {
  32777. shape: shape,
  32778. path: path,
  32779. scale: scale,
  32780. rotation: rotation,
  32781. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32782. sideOrientation: sideOrientation,
  32783. instance: instance,
  32784. updatable: updatable
  32785. };
  32786. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  32787. };
  32788. /**
  32789. * Creates an custom extruded shape mesh.
  32790. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  32791. * Please consider using the same method from the MeshBuilder class instead.
  32792. *
  32793. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32794. * 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
  32795. * extruded along the Z axis.
  32796. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32797. * 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
  32798. * and the distance of this point from the begining of the path :
  32799. * ```javascript
  32800. * var rotationFunction = function(i, distance) {
  32801. * // do things
  32802. * return rotationValue; }
  32803. * ```
  32804. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  32805. * 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
  32806. * and the distance of this point from the begining of the path :
  32807. * ```javascript
  32808. * var scaleFunction = function(i, distance) {
  32809. * // do things
  32810. * return scaleValue;}
  32811. * ```
  32812. * It must returns a float value that will be the scale value applied to the shape on each path point.
  32813. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  32814. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  32815. * 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
  32816. * 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
  32817. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32819. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32821. */
  32822. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  32823. var options = {
  32824. shape: shape,
  32825. path: path,
  32826. scaleFunction: scaleFunction,
  32827. rotationFunction: rotationFunction,
  32828. ribbonCloseArray: ribbonCloseArray,
  32829. ribbonClosePath: ribbonClosePath,
  32830. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32831. sideOrientation: sideOrientation,
  32832. instance: instance,
  32833. updatable: updatable
  32834. };
  32835. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  32836. };
  32837. /**
  32838. * Creates lathe mesh.
  32839. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  32840. * Please consider using the same method from the MeshBuilder class instead.
  32841. * 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
  32842. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  32843. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  32844. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  32845. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32846. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32848. */
  32849. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  32850. var options = {
  32851. shape: shape,
  32852. radius: radius,
  32853. tessellation: tessellation,
  32854. sideOrientation: sideOrientation,
  32855. updatable: updatable
  32856. };
  32857. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  32858. };
  32859. /**
  32860. * Creates a plane mesh.
  32861. * Please consider using the same method from the MeshBuilder class instead.
  32862. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  32863. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32864. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32865. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32866. */
  32867. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  32868. var options = {
  32869. size: size,
  32870. width: size,
  32871. height: size,
  32872. sideOrientation: sideOrientation,
  32873. updatable: updatable
  32874. };
  32875. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  32876. };
  32877. /**
  32878. * Creates a ground mesh.
  32879. * Please consider using the same method from the MeshBuilder class instead.
  32880. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  32881. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  32882. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32883. */
  32884. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  32885. var options = {
  32886. width: width,
  32887. height: height,
  32888. subdivisions: subdivisions,
  32889. updatable: updatable
  32890. };
  32891. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  32892. };
  32893. /**
  32894. * Creates a tiled ground mesh.
  32895. * Please consider using the same method from the MeshBuilder class instead.
  32896. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  32897. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  32898. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  32899. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  32900. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  32901. * numbers of subdivisions on the ground width and height of each tile.
  32902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32903. */
  32904. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  32905. var options = {
  32906. xmin: xmin,
  32907. zmin: zmin,
  32908. xmax: xmax,
  32909. zmax: zmax,
  32910. subdivisions: subdivisions,
  32911. precision: precision,
  32912. updatable: updatable
  32913. };
  32914. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  32915. };
  32916. /**
  32917. * Creates a ground mesh from a height map.
  32918. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  32919. * Please consider using the same method from the MeshBuilder class instead.
  32920. * The parameter `url` sets the URL of the height map image resource.
  32921. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  32922. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  32923. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  32924. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  32925. * 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).
  32926. * This function is passed the newly built mesh :
  32927. * ```javascript
  32928. * function(mesh) { // do things
  32929. * return; }
  32930. * ```
  32931. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32932. */
  32933. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  32934. var options = {
  32935. width: width,
  32936. height: height,
  32937. subdivisions: subdivisions,
  32938. minHeight: minHeight,
  32939. maxHeight: maxHeight,
  32940. updatable: updatable,
  32941. onReady: onReady
  32942. };
  32943. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  32944. };
  32945. /**
  32946. * Creates a tube mesh.
  32947. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  32948. * Please consider using the same method from the MeshBuilder class instead.
  32949. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  32950. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  32951. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  32952. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  32953. * 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.
  32954. * It must return a radius value (positive float) :
  32955. * ```javascript
  32956. * var radiusFunction = function(i, distance) {
  32957. * // do things
  32958. * return radius; }
  32959. * ```
  32960. * 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
  32961. * 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
  32962. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32963. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32964. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32965. */
  32966. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  32967. var options = {
  32968. path: path,
  32969. radius: radius,
  32970. tessellation: tessellation,
  32971. radiusFunction: radiusFunction,
  32972. arc: 1,
  32973. cap: cap,
  32974. updatable: updatable,
  32975. sideOrientation: sideOrientation,
  32976. instance: instance
  32977. };
  32978. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  32979. };
  32980. /**
  32981. * Creates a polyhedron mesh.
  32982. * Please consider using the same method from the MeshBuilder class instead.
  32983. * 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
  32984. * to choose the wanted type.
  32985. * The parameter `size` (positive float, default 1) sets the polygon size.
  32986. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  32987. * 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`.
  32988. * 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
  32989. * 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)`).
  32990. * 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
  32991. * 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.
  32992. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32993. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32994. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32995. */
  32996. Mesh.CreatePolyhedron = function (name, options, scene) {
  32997. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  32998. };
  32999. /**
  33000. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33001. * Please consider using the same method from the MeshBuilder class instead.
  33002. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33003. * 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`).
  33004. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33005. * 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.
  33006. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33007. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33008. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33009. */
  33010. Mesh.CreateIcoSphere = function (name, options, scene) {
  33011. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33012. };
  33013. /**
  33014. * Creates a decal mesh.
  33015. * Please consider using the same method from the MeshBuilder class instead.
  33016. * 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.
  33017. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33018. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33019. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33020. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33021. */
  33022. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33023. var options = {
  33024. position: position,
  33025. normal: normal,
  33026. size: size,
  33027. angle: angle
  33028. };
  33029. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33030. };
  33031. // Skeletons
  33032. /**
  33033. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33034. */
  33035. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33036. if (!this._sourcePositions) {
  33037. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33038. if (!source) {
  33039. return this._sourcePositions;
  33040. }
  33041. this._sourcePositions = new Float32Array(source);
  33042. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33043. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33044. }
  33045. }
  33046. return this._sourcePositions;
  33047. };
  33048. /**
  33049. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33050. */
  33051. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33052. if (!this._sourceNormals) {
  33053. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33054. if (!source) {
  33055. return this._sourceNormals;
  33056. }
  33057. this._sourceNormals = new Float32Array(source);
  33058. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33059. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33060. }
  33061. }
  33062. return this._sourceNormals;
  33063. };
  33064. /**
  33065. * Updates the vertex buffer by applying transformation from the bones.
  33066. * Returns the Mesh.
  33067. *
  33068. * @param {skeleton} skeleton to apply
  33069. */
  33070. Mesh.prototype.applySkeleton = function (skeleton) {
  33071. if (!this.geometry) {
  33072. return this;
  33073. }
  33074. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33075. return this;
  33076. }
  33077. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33078. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33079. return this;
  33080. }
  33081. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33082. return this;
  33083. }
  33084. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33085. return this;
  33086. }
  33087. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33088. return this;
  33089. }
  33090. if (!this._sourcePositions) {
  33091. var submeshes = this.subMeshes.slice();
  33092. this.setPositionsForCPUSkinning();
  33093. this.subMeshes = submeshes;
  33094. }
  33095. if (!this._sourceNormals) {
  33096. this.setNormalsForCPUSkinning();
  33097. }
  33098. // positionsData checks for not being Float32Array will only pass at most once
  33099. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33100. if (!positionsData) {
  33101. return this;
  33102. }
  33103. if (!(positionsData instanceof Float32Array)) {
  33104. positionsData = new Float32Array(positionsData);
  33105. }
  33106. // normalsData checks for not being Float32Array will only pass at most once
  33107. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33108. if (!normalsData) {
  33109. return this;
  33110. }
  33111. if (!(normalsData instanceof Float32Array)) {
  33112. normalsData = new Float32Array(normalsData);
  33113. }
  33114. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33115. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33116. if (!matricesWeightsData || !matricesIndicesData) {
  33117. return this;
  33118. }
  33119. var needExtras = this.numBoneInfluencers > 4;
  33120. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33121. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33122. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33123. var tempVector3 = BABYLON.Vector3.Zero();
  33124. var finalMatrix = new BABYLON.Matrix();
  33125. var tempMatrix = new BABYLON.Matrix();
  33126. var matWeightIdx = 0;
  33127. var inf;
  33128. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33129. var weight;
  33130. for (inf = 0; inf < 4; inf++) {
  33131. weight = matricesWeightsData[matWeightIdx + inf];
  33132. if (weight > 0) {
  33133. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33134. finalMatrix.addToSelf(tempMatrix);
  33135. }
  33136. else
  33137. break;
  33138. }
  33139. if (needExtras) {
  33140. for (inf = 0; inf < 4; inf++) {
  33141. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33142. if (weight > 0) {
  33143. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33144. finalMatrix.addToSelf(tempMatrix);
  33145. }
  33146. else
  33147. break;
  33148. }
  33149. }
  33150. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33151. tempVector3.toArray(positionsData, index);
  33152. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33153. tempVector3.toArray(normalsData, index);
  33154. finalMatrix.reset();
  33155. }
  33156. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33157. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33158. return this;
  33159. };
  33160. // Tools
  33161. /**
  33162. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33163. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33164. */
  33165. Mesh.MinMax = function (meshes) {
  33166. var minVector = null;
  33167. var maxVector = null;
  33168. meshes.forEach(function (mesh, index, array) {
  33169. var boundingInfo = mesh.getBoundingInfo();
  33170. var boundingBox = boundingInfo.boundingBox;
  33171. if (!minVector || !maxVector) {
  33172. minVector = boundingBox.minimumWorld;
  33173. maxVector = boundingBox.maximumWorld;
  33174. }
  33175. else {
  33176. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33177. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33178. }
  33179. });
  33180. if (!minVector || !maxVector) {
  33181. return {
  33182. min: BABYLON.Vector3.Zero(),
  33183. max: BABYLON.Vector3.Zero()
  33184. };
  33185. }
  33186. return {
  33187. min: minVector,
  33188. max: maxVector
  33189. };
  33190. };
  33191. /**
  33192. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33193. */
  33194. Mesh.Center = function (meshesOrMinMaxVector) {
  33195. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33196. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33197. };
  33198. /**
  33199. * Merge the array of meshes into a single mesh for performance reasons.
  33200. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33201. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33202. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33203. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33204. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33205. */
  33206. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33207. if (disposeSource === void 0) { disposeSource = true; }
  33208. var index;
  33209. if (!allow32BitsIndices) {
  33210. var totalVertices = 0;
  33211. // Counting vertices
  33212. for (index = 0; index < meshes.length; index++) {
  33213. if (meshes[index]) {
  33214. totalVertices += meshes[index].getTotalVertices();
  33215. if (totalVertices > 65536) {
  33216. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33217. return null;
  33218. }
  33219. }
  33220. }
  33221. }
  33222. // Merge
  33223. var vertexData = null;
  33224. var otherVertexData;
  33225. var indiceArray = new Array();
  33226. var source = null;
  33227. for (index = 0; index < meshes.length; index++) {
  33228. if (meshes[index]) {
  33229. meshes[index].computeWorldMatrix(true);
  33230. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33231. otherVertexData.transform(meshes[index].getWorldMatrix());
  33232. if (vertexData) {
  33233. vertexData.merge(otherVertexData);
  33234. }
  33235. else {
  33236. vertexData = otherVertexData;
  33237. source = meshes[index];
  33238. }
  33239. if (subdivideWithSubMeshes) {
  33240. indiceArray.push(meshes[index].getTotalIndices());
  33241. }
  33242. }
  33243. }
  33244. source = source;
  33245. if (!meshSubclass) {
  33246. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33247. }
  33248. vertexData.applyToMesh(meshSubclass);
  33249. // Setting properties
  33250. meshSubclass.material = source.material;
  33251. meshSubclass.checkCollisions = source.checkCollisions;
  33252. // Cleaning
  33253. if (disposeSource) {
  33254. for (index = 0; index < meshes.length; index++) {
  33255. if (meshes[index]) {
  33256. meshes[index].dispose();
  33257. }
  33258. }
  33259. }
  33260. // Subdivide
  33261. if (subdivideWithSubMeshes) {
  33262. //-- Suppresions du submesh global
  33263. meshSubclass.releaseSubMeshes();
  33264. index = 0;
  33265. var offset = 0;
  33266. //-- aplique la subdivision en fonction du tableau d'indices
  33267. while (index < indiceArray.length) {
  33268. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33269. offset += indiceArray[index];
  33270. index++;
  33271. }
  33272. }
  33273. return meshSubclass;
  33274. };
  33275. // Consts
  33276. Mesh._FRONTSIDE = 0;
  33277. Mesh._BACKSIDE = 1;
  33278. Mesh._DOUBLESIDE = 2;
  33279. Mesh._DEFAULTSIDE = 0;
  33280. Mesh._NO_CAP = 0;
  33281. Mesh._CAP_START = 1;
  33282. Mesh._CAP_END = 2;
  33283. Mesh._CAP_ALL = 3;
  33284. return Mesh;
  33285. }(BABYLON.AbstractMesh));
  33286. BABYLON.Mesh = Mesh;
  33287. })(BABYLON || (BABYLON = {}));
  33288. //# sourceMappingURL=babylon.mesh.js.map
  33289. "use strict";
  33290. var BABYLON;
  33291. (function (BABYLON) {
  33292. var BaseSubMesh = /** @class */ (function () {
  33293. function BaseSubMesh() {
  33294. }
  33295. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33296. get: function () {
  33297. return this._materialEffect;
  33298. },
  33299. enumerable: true,
  33300. configurable: true
  33301. });
  33302. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33303. if (defines === void 0) { defines = null; }
  33304. if (this._materialEffect === effect) {
  33305. if (!effect) {
  33306. this._materialDefines = null;
  33307. }
  33308. return;
  33309. }
  33310. this._materialDefines = defines;
  33311. this._materialEffect = effect;
  33312. };
  33313. return BaseSubMesh;
  33314. }());
  33315. BABYLON.BaseSubMesh = BaseSubMesh;
  33316. var SubMesh = /** @class */ (function (_super) {
  33317. __extends(SubMesh, _super);
  33318. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33319. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33320. var _this = _super.call(this) || this;
  33321. _this.materialIndex = materialIndex;
  33322. _this.verticesStart = verticesStart;
  33323. _this.verticesCount = verticesCount;
  33324. _this.indexStart = indexStart;
  33325. _this.indexCount = indexCount;
  33326. _this._renderId = 0;
  33327. _this._mesh = mesh;
  33328. _this._renderingMesh = renderingMesh || mesh;
  33329. mesh.subMeshes.push(_this);
  33330. _this._trianglePlanes = [];
  33331. _this._id = mesh.subMeshes.length - 1;
  33332. if (createBoundingBox) {
  33333. _this.refreshBoundingInfo();
  33334. mesh.computeWorldMatrix(true);
  33335. }
  33336. return _this;
  33337. }
  33338. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33339. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33340. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33341. };
  33342. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33343. get: function () {
  33344. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33345. },
  33346. enumerable: true,
  33347. configurable: true
  33348. });
  33349. /**
  33350. * Returns the submesh BoudingInfo object.
  33351. */
  33352. SubMesh.prototype.getBoundingInfo = function () {
  33353. if (this.IsGlobal) {
  33354. return this._mesh.getBoundingInfo();
  33355. }
  33356. return this._boundingInfo;
  33357. };
  33358. /**
  33359. * Sets the submesh BoundingInfo.
  33360. * Return the SubMesh.
  33361. */
  33362. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33363. this._boundingInfo = boundingInfo;
  33364. return this;
  33365. };
  33366. /**
  33367. * Returns the mesh of the current submesh.
  33368. */
  33369. SubMesh.prototype.getMesh = function () {
  33370. return this._mesh;
  33371. };
  33372. /**
  33373. * Returns the rendering mesh of the submesh.
  33374. */
  33375. SubMesh.prototype.getRenderingMesh = function () {
  33376. return this._renderingMesh;
  33377. };
  33378. /**
  33379. * Returns the submesh material.
  33380. */
  33381. SubMesh.prototype.getMaterial = function () {
  33382. var rootMaterial = this._renderingMesh.material;
  33383. if (rootMaterial === null || rootMaterial === undefined) {
  33384. return this._mesh.getScene().defaultMaterial;
  33385. }
  33386. else if (rootMaterial.getSubMaterial) {
  33387. var multiMaterial = rootMaterial;
  33388. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33389. if (this._currentMaterial !== effectiveMaterial) {
  33390. this._currentMaterial = effectiveMaterial;
  33391. this._materialDefines = null;
  33392. }
  33393. return effectiveMaterial;
  33394. }
  33395. return rootMaterial;
  33396. };
  33397. // Methods
  33398. /**
  33399. * Sets a new updated BoundingInfo object to the submesh.
  33400. * Returns the SubMesh.
  33401. */
  33402. SubMesh.prototype.refreshBoundingInfo = function () {
  33403. this._lastColliderWorldVertices = null;
  33404. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33405. return this;
  33406. }
  33407. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33408. if (!data) {
  33409. this._boundingInfo = this._mesh.getBoundingInfo();
  33410. return this;
  33411. }
  33412. var indices = this._renderingMesh.getIndices();
  33413. var extend;
  33414. //is this the only submesh?
  33415. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33416. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33417. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33418. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33419. }
  33420. else {
  33421. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33422. }
  33423. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33424. return this;
  33425. };
  33426. SubMesh.prototype._checkCollision = function (collider) {
  33427. var boundingInfo = this.getBoundingInfo();
  33428. return boundingInfo._checkCollision(collider);
  33429. };
  33430. /**
  33431. * Updates the submesh BoundingInfo.
  33432. * Returns the Submesh.
  33433. */
  33434. SubMesh.prototype.updateBoundingInfo = function (world) {
  33435. var boundingInfo = this.getBoundingInfo();
  33436. if (!boundingInfo) {
  33437. this.refreshBoundingInfo();
  33438. boundingInfo = this.getBoundingInfo();
  33439. }
  33440. boundingInfo.update(world);
  33441. return this;
  33442. };
  33443. /**
  33444. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33445. * Boolean returned.
  33446. */
  33447. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33448. var boundingInfo = this.getBoundingInfo();
  33449. if (!boundingInfo) {
  33450. return false;
  33451. }
  33452. return boundingInfo.isInFrustum(frustumPlanes);
  33453. };
  33454. /**
  33455. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33456. * Boolean returned.
  33457. */
  33458. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33459. var boundingInfo = this.getBoundingInfo();
  33460. if (!boundingInfo) {
  33461. return false;
  33462. }
  33463. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33464. };
  33465. /**
  33466. * Renders the submesh.
  33467. * Returns it.
  33468. */
  33469. SubMesh.prototype.render = function (enableAlphaMode) {
  33470. this._renderingMesh.render(this, enableAlphaMode);
  33471. return this;
  33472. };
  33473. /**
  33474. * Returns a new Index Buffer.
  33475. * Type returned : WebGLBuffer.
  33476. */
  33477. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33478. if (!this._linesIndexBuffer) {
  33479. var linesIndices = [];
  33480. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33481. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33482. }
  33483. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33484. this.linesIndexCount = linesIndices.length;
  33485. }
  33486. return this._linesIndexBuffer;
  33487. };
  33488. /**
  33489. * True is the passed Ray intersects the submesh bounding box.
  33490. * Boolean returned.
  33491. */
  33492. SubMesh.prototype.canIntersects = function (ray) {
  33493. var boundingInfo = this.getBoundingInfo();
  33494. if (!boundingInfo) {
  33495. return false;
  33496. }
  33497. return ray.intersectsBox(boundingInfo.boundingBox);
  33498. };
  33499. /**
  33500. * Returns an object IntersectionInfo.
  33501. */
  33502. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33503. var intersectInfo = null;
  33504. var material = this.getMaterial();
  33505. if (!material) {
  33506. return null;
  33507. }
  33508. switch (material.fillMode) {
  33509. case BABYLON.Material.PointListDrawMode:
  33510. case BABYLON.Material.LineListDrawMode:
  33511. case BABYLON.Material.LineLoopDrawMode:
  33512. case BABYLON.Material.LineStripDrawMode:
  33513. case BABYLON.Material.TriangleFanDrawMode:
  33514. case BABYLON.Material.TriangleStripDrawMode:
  33515. return null;
  33516. }
  33517. // LineMesh first as it's also a Mesh...
  33518. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33519. var lineMesh = this._mesh;
  33520. // Line test
  33521. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33522. var p0 = positions[indices[index]];
  33523. var p1 = positions[indices[index + 1]];
  33524. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33525. if (length < 0) {
  33526. continue;
  33527. }
  33528. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33529. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33530. if (fastCheck) {
  33531. break;
  33532. }
  33533. }
  33534. }
  33535. }
  33536. else {
  33537. // Triangles test
  33538. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33539. var p0 = positions[indices[index]];
  33540. var p1 = positions[indices[index + 1]];
  33541. var p2 = positions[indices[index + 2]];
  33542. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33543. if (currentIntersectInfo) {
  33544. if (currentIntersectInfo.distance < 0) {
  33545. continue;
  33546. }
  33547. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33548. intersectInfo = currentIntersectInfo;
  33549. intersectInfo.faceId = index / 3;
  33550. if (fastCheck) {
  33551. break;
  33552. }
  33553. }
  33554. }
  33555. }
  33556. }
  33557. return intersectInfo;
  33558. };
  33559. SubMesh.prototype._rebuild = function () {
  33560. if (this._linesIndexBuffer) {
  33561. this._linesIndexBuffer = null;
  33562. }
  33563. };
  33564. // Clone
  33565. /**
  33566. * Creates a new Submesh from the passed Mesh.
  33567. */
  33568. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33569. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33570. if (!this.IsGlobal) {
  33571. var boundingInfo = this.getBoundingInfo();
  33572. if (!boundingInfo) {
  33573. return result;
  33574. }
  33575. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33576. }
  33577. return result;
  33578. };
  33579. // Dispose
  33580. /**
  33581. * Disposes the Submesh.
  33582. * Returns nothing.
  33583. */
  33584. SubMesh.prototype.dispose = function () {
  33585. if (this._linesIndexBuffer) {
  33586. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33587. this._linesIndexBuffer = null;
  33588. }
  33589. // Remove from mesh
  33590. var index = this._mesh.subMeshes.indexOf(this);
  33591. this._mesh.subMeshes.splice(index, 1);
  33592. };
  33593. // Statics
  33594. /**
  33595. * Creates a new Submesh from the passed parameters :
  33596. * - materialIndex (integer) : the index of the main mesh material.
  33597. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33598. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33599. * - mesh (Mesh) : the main mesh to create the submesh from.
  33600. * - renderingMesh (optional Mesh) : rendering mesh.
  33601. */
  33602. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33603. var minVertexIndex = Number.MAX_VALUE;
  33604. var maxVertexIndex = -Number.MAX_VALUE;
  33605. renderingMesh = (renderingMesh || mesh);
  33606. var indices = renderingMesh.getIndices();
  33607. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33608. var vertexIndex = indices[index];
  33609. if (vertexIndex < minVertexIndex)
  33610. minVertexIndex = vertexIndex;
  33611. if (vertexIndex > maxVertexIndex)
  33612. maxVertexIndex = vertexIndex;
  33613. }
  33614. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33615. };
  33616. return SubMesh;
  33617. }(BaseSubMesh));
  33618. BABYLON.SubMesh = SubMesh;
  33619. })(BABYLON || (BABYLON = {}));
  33620. //# sourceMappingURL=babylon.subMesh.js.map
  33621. "use strict";
  33622. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33623. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33624. s = arguments[i];
  33625. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33626. t[p] = s[p];
  33627. }
  33628. return t;
  33629. };
  33630. var BABYLON;
  33631. (function (BABYLON) {
  33632. /**
  33633. * Manages the defines for the Material
  33634. */
  33635. var MaterialDefines = /** @class */ (function () {
  33636. function MaterialDefines() {
  33637. this._isDirty = true;
  33638. /** @ignore */
  33639. this._areLightsDirty = true;
  33640. /** @ignore */
  33641. this._areAttributesDirty = true;
  33642. /** @ignore */
  33643. this._areTexturesDirty = true;
  33644. /** @ignore */
  33645. this._areFresnelDirty = true;
  33646. /** @ignore */
  33647. this._areMiscDirty = true;
  33648. /** @ignore */
  33649. this._areImageProcessingDirty = true;
  33650. /** @ignore */
  33651. this._normals = false;
  33652. /** @ignore */
  33653. this._uvs = false;
  33654. /** @ignore */
  33655. this._needNormals = false;
  33656. /** @ignore */
  33657. this._needUVs = false;
  33658. }
  33659. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33660. /**
  33661. * Specifies if the material needs to be re-calculated
  33662. */
  33663. get: function () {
  33664. return this._isDirty;
  33665. },
  33666. enumerable: true,
  33667. configurable: true
  33668. });
  33669. /**
  33670. * Marks the material to indicate that it has been re-calculated
  33671. */
  33672. MaterialDefines.prototype.markAsProcessed = function () {
  33673. this._isDirty = false;
  33674. this._areAttributesDirty = false;
  33675. this._areTexturesDirty = false;
  33676. this._areFresnelDirty = false;
  33677. this._areLightsDirty = false;
  33678. this._areMiscDirty = false;
  33679. this._areImageProcessingDirty = false;
  33680. };
  33681. /**
  33682. * Marks the material to indicate that it needs to be re-calculated
  33683. */
  33684. MaterialDefines.prototype.markAsUnprocessed = function () {
  33685. this._isDirty = true;
  33686. };
  33687. /**
  33688. * Marks the material to indicate all of its defines need to be re-calculated
  33689. */
  33690. MaterialDefines.prototype.markAllAsDirty = function () {
  33691. this._areTexturesDirty = true;
  33692. this._areAttributesDirty = true;
  33693. this._areLightsDirty = true;
  33694. this._areFresnelDirty = true;
  33695. this._areMiscDirty = true;
  33696. this._areImageProcessingDirty = true;
  33697. this._isDirty = true;
  33698. };
  33699. /**
  33700. * Marks the material to indicate that image processing needs to be re-calculated
  33701. */
  33702. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  33703. this._areImageProcessingDirty = true;
  33704. this._isDirty = true;
  33705. };
  33706. /**
  33707. * Marks the material to indicate the lights need to be re-calculated
  33708. */
  33709. MaterialDefines.prototype.markAsLightDirty = function () {
  33710. this._areLightsDirty = true;
  33711. this._isDirty = true;
  33712. };
  33713. /**
  33714. * Marks the attribute state as changed
  33715. */
  33716. MaterialDefines.prototype.markAsAttributesDirty = function () {
  33717. this._areAttributesDirty = true;
  33718. this._isDirty = true;
  33719. };
  33720. /**
  33721. * Marks the texture state as changed
  33722. */
  33723. MaterialDefines.prototype.markAsTexturesDirty = function () {
  33724. this._areTexturesDirty = true;
  33725. this._isDirty = true;
  33726. };
  33727. /**
  33728. * Marks the fresnel state as changed
  33729. */
  33730. MaterialDefines.prototype.markAsFresnelDirty = function () {
  33731. this._areFresnelDirty = true;
  33732. this._isDirty = true;
  33733. };
  33734. /**
  33735. * Marks the misc state as changed
  33736. */
  33737. MaterialDefines.prototype.markAsMiscDirty = function () {
  33738. this._areMiscDirty = true;
  33739. this._isDirty = true;
  33740. };
  33741. /**
  33742. * Rebuilds the material defines
  33743. */
  33744. MaterialDefines.prototype.rebuild = function () {
  33745. if (this._keys) {
  33746. delete this._keys;
  33747. }
  33748. this._keys = [];
  33749. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  33750. var key = _a[_i];
  33751. if (key[0] === "_") {
  33752. continue;
  33753. }
  33754. this._keys.push(key);
  33755. }
  33756. };
  33757. /**
  33758. * Specifies if two material defines are equal
  33759. * @param other - A material define instance to compare to
  33760. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  33761. */
  33762. MaterialDefines.prototype.isEqual = function (other) {
  33763. if (this._keys.length !== other._keys.length) {
  33764. return false;
  33765. }
  33766. for (var index = 0; index < this._keys.length; index++) {
  33767. var prop = this._keys[index];
  33768. if (this[prop] !== other[prop]) {
  33769. return false;
  33770. }
  33771. }
  33772. return true;
  33773. };
  33774. /**
  33775. * Clones this instance's defines to another instance
  33776. * @param other - material defines to clone values to
  33777. */
  33778. MaterialDefines.prototype.cloneTo = function (other) {
  33779. if (this._keys.length !== other._keys.length) {
  33780. other._keys = this._keys.slice(0);
  33781. }
  33782. for (var index = 0; index < this._keys.length; index++) {
  33783. var prop = this._keys[index];
  33784. other[prop] = this[prop];
  33785. }
  33786. };
  33787. /**
  33788. * Resets the material define values
  33789. */
  33790. MaterialDefines.prototype.reset = function () {
  33791. for (var index = 0; index < this._keys.length; index++) {
  33792. var prop = this._keys[index];
  33793. var type = typeof this[prop];
  33794. switch (type) {
  33795. case "number":
  33796. this[prop] = 0;
  33797. break;
  33798. case "string":
  33799. this[prop] = "";
  33800. break;
  33801. default:
  33802. this[prop] = false;
  33803. break;
  33804. }
  33805. }
  33806. };
  33807. /**
  33808. * Converts the material define values to a string
  33809. * @returns - String of material define information
  33810. */
  33811. MaterialDefines.prototype.toString = function () {
  33812. var result = "";
  33813. for (var index = 0; index < this._keys.length; index++) {
  33814. var prop = this._keys[index];
  33815. var value = this[prop];
  33816. var type = typeof value;
  33817. switch (type) {
  33818. case "number":
  33819. case "string":
  33820. result += "#define " + prop + " " + value + "\n";
  33821. break;
  33822. default:
  33823. if (value) {
  33824. result += "#define " + prop + "\n";
  33825. }
  33826. break;
  33827. }
  33828. }
  33829. return result;
  33830. };
  33831. return MaterialDefines;
  33832. }());
  33833. BABYLON.MaterialDefines = MaterialDefines;
  33834. /**
  33835. * Base class for the main features of a material in Babylon.js
  33836. */
  33837. var Material = /** @class */ (function () {
  33838. /**
  33839. * Creates a material instance
  33840. * @param name defines the name of the material
  33841. * @param scene defines the scene to reference
  33842. * @param doNotAdd specifies if the material should be added to the scene
  33843. */
  33844. function Material(name, scene, doNotAdd) {
  33845. /**
  33846. * Specifies if the ready state should be checked on each call
  33847. */
  33848. this.checkReadyOnEveryCall = false;
  33849. /**
  33850. * Specifies if the ready state should be checked once
  33851. */
  33852. this.checkReadyOnlyOnce = false;
  33853. /**
  33854. * The state of the material
  33855. */
  33856. this.state = "";
  33857. /**
  33858. * The alpha value of the material
  33859. */
  33860. this._alpha = 1.0;
  33861. /**
  33862. * Specifies if back face culling is enabled
  33863. */
  33864. this._backFaceCulling = true;
  33865. /**
  33866. * Specifies if the material should be serialized
  33867. */
  33868. this.doNotSerialize = false;
  33869. /**
  33870. * Specifies if the effect should be stored on sub meshes
  33871. */
  33872. this.storeEffectOnSubMeshes = false;
  33873. /**
  33874. * An event triggered when the material is disposed
  33875. */
  33876. this.onDisposeObservable = new BABYLON.Observable();
  33877. /**
  33878. * An event triggered when the material is bound
  33879. */
  33880. this.onBindObservable = new BABYLON.Observable();
  33881. /**
  33882. * An event triggered when the material is unbound
  33883. */
  33884. this.onUnBindObservable = new BABYLON.Observable();
  33885. /**
  33886. * Stores the value of the alpha mode
  33887. */
  33888. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  33889. /**
  33890. * Stores the state of the need depth pre-pass value
  33891. */
  33892. this._needDepthPrePass = false;
  33893. /**
  33894. * Specifies if depth writing should be disabled
  33895. */
  33896. this.disableDepthWrite = false;
  33897. /**
  33898. * Specifies if depth writing should be forced
  33899. */
  33900. this.forceDepthWrite = false;
  33901. /**
  33902. * Specifies if there should be a separate pass for culling
  33903. */
  33904. this.separateCullingPass = false;
  33905. /**
  33906. * Stores the state specifing if fog should be enabled
  33907. */
  33908. this._fogEnabled = true;
  33909. /**
  33910. * Stores the size of points
  33911. */
  33912. this.pointSize = 1.0;
  33913. /**
  33914. * Stores the z offset value
  33915. */
  33916. this.zOffset = 0;
  33917. /**
  33918. * Specifies if the material was previously ready
  33919. */
  33920. this._wasPreviouslyReady = false;
  33921. /**
  33922. * Stores the fill mode state
  33923. */
  33924. this._fillMode = Material.TriangleFillMode;
  33925. this.name = name;
  33926. this.id = name || BABYLON.Tools.RandomId();
  33927. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  33928. if (this._scene.useRightHandedSystem) {
  33929. this.sideOrientation = Material.ClockWiseSideOrientation;
  33930. }
  33931. else {
  33932. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  33933. }
  33934. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  33935. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  33936. if (!doNotAdd) {
  33937. this._scene.materials.push(this);
  33938. }
  33939. }
  33940. Object.defineProperty(Material, "TriangleFillMode", {
  33941. /**
  33942. * Returns the triangle fill mode
  33943. */
  33944. get: function () {
  33945. return Material._TriangleFillMode;
  33946. },
  33947. enumerable: true,
  33948. configurable: true
  33949. });
  33950. Object.defineProperty(Material, "WireFrameFillMode", {
  33951. /**
  33952. * Returns the wireframe mode
  33953. */
  33954. get: function () {
  33955. return Material._WireFrameFillMode;
  33956. },
  33957. enumerable: true,
  33958. configurable: true
  33959. });
  33960. Object.defineProperty(Material, "PointFillMode", {
  33961. /**
  33962. * Returns the point fill mode
  33963. */
  33964. get: function () {
  33965. return Material._PointFillMode;
  33966. },
  33967. enumerable: true,
  33968. configurable: true
  33969. });
  33970. Object.defineProperty(Material, "PointListDrawMode", {
  33971. /**
  33972. * Returns the point list draw mode
  33973. */
  33974. get: function () {
  33975. return Material._PointListDrawMode;
  33976. },
  33977. enumerable: true,
  33978. configurable: true
  33979. });
  33980. Object.defineProperty(Material, "LineListDrawMode", {
  33981. /**
  33982. * Returns the line list draw mode
  33983. */
  33984. get: function () {
  33985. return Material._LineListDrawMode;
  33986. },
  33987. enumerable: true,
  33988. configurable: true
  33989. });
  33990. Object.defineProperty(Material, "LineLoopDrawMode", {
  33991. /**
  33992. * Returns the line loop draw mode
  33993. */
  33994. get: function () {
  33995. return Material._LineLoopDrawMode;
  33996. },
  33997. enumerable: true,
  33998. configurable: true
  33999. });
  34000. Object.defineProperty(Material, "LineStripDrawMode", {
  34001. /**
  34002. * Returns the line strip draw mode
  34003. */
  34004. get: function () {
  34005. return Material._LineStripDrawMode;
  34006. },
  34007. enumerable: true,
  34008. configurable: true
  34009. });
  34010. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34011. /**
  34012. * Returns the triangle strip draw mode
  34013. */
  34014. get: function () {
  34015. return Material._TriangleStripDrawMode;
  34016. },
  34017. enumerable: true,
  34018. configurable: true
  34019. });
  34020. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34021. /**
  34022. * Returns the triangle fan draw mode
  34023. */
  34024. get: function () {
  34025. return Material._TriangleFanDrawMode;
  34026. },
  34027. enumerable: true,
  34028. configurable: true
  34029. });
  34030. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34031. /**
  34032. * Returns the clock-wise side orientation
  34033. */
  34034. get: function () {
  34035. return Material._ClockWiseSideOrientation;
  34036. },
  34037. enumerable: true,
  34038. configurable: true
  34039. });
  34040. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34041. /**
  34042. * Returns the counter clock-wise side orientation
  34043. */
  34044. get: function () {
  34045. return Material._CounterClockWiseSideOrientation;
  34046. },
  34047. enumerable: true,
  34048. configurable: true
  34049. });
  34050. Object.defineProperty(Material, "TextureDirtyFlag", {
  34051. /**
  34052. * Returns the dirty texture flag value
  34053. */
  34054. get: function () {
  34055. return Material._TextureDirtyFlag;
  34056. },
  34057. enumerable: true,
  34058. configurable: true
  34059. });
  34060. Object.defineProperty(Material, "LightDirtyFlag", {
  34061. /**
  34062. * Returns the dirty light flag value
  34063. */
  34064. get: function () {
  34065. return Material._LightDirtyFlag;
  34066. },
  34067. enumerable: true,
  34068. configurable: true
  34069. });
  34070. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34071. /**
  34072. * Returns the dirty fresnel flag value
  34073. */
  34074. get: function () {
  34075. return Material._FresnelDirtyFlag;
  34076. },
  34077. enumerable: true,
  34078. configurable: true
  34079. });
  34080. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34081. /**
  34082. * Returns the dirty attributes flag value
  34083. */
  34084. get: function () {
  34085. return Material._AttributesDirtyFlag;
  34086. },
  34087. enumerable: true,
  34088. configurable: true
  34089. });
  34090. Object.defineProperty(Material, "MiscDirtyFlag", {
  34091. /**
  34092. * Returns the dirty misc flag value
  34093. */
  34094. get: function () {
  34095. return Material._MiscDirtyFlag;
  34096. },
  34097. enumerable: true,
  34098. configurable: true
  34099. });
  34100. Object.defineProperty(Material.prototype, "alpha", {
  34101. /**
  34102. * Gets the alpha value of the material
  34103. */
  34104. get: function () {
  34105. return this._alpha;
  34106. },
  34107. /**
  34108. * Sets the alpha value of the material
  34109. */
  34110. set: function (value) {
  34111. if (this._alpha === value) {
  34112. return;
  34113. }
  34114. this._alpha = value;
  34115. this.markAsDirty(Material.MiscDirtyFlag);
  34116. },
  34117. enumerable: true,
  34118. configurable: true
  34119. });
  34120. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34121. /**
  34122. * Gets the back-face culling state
  34123. */
  34124. get: function () {
  34125. return this._backFaceCulling;
  34126. },
  34127. /**
  34128. * Sets the back-face culling state
  34129. */
  34130. set: function (value) {
  34131. if (this._backFaceCulling === value) {
  34132. return;
  34133. }
  34134. this._backFaceCulling = value;
  34135. this.markAsDirty(Material.TextureDirtyFlag);
  34136. },
  34137. enumerable: true,
  34138. configurable: true
  34139. });
  34140. Object.defineProperty(Material.prototype, "onDispose", {
  34141. /**
  34142. * Called during a dispose event
  34143. */
  34144. set: function (callback) {
  34145. if (this._onDisposeObserver) {
  34146. this.onDisposeObservable.remove(this._onDisposeObserver);
  34147. }
  34148. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34149. },
  34150. enumerable: true,
  34151. configurable: true
  34152. });
  34153. Object.defineProperty(Material.prototype, "onBind", {
  34154. /**
  34155. * Called during a bind event
  34156. */
  34157. set: function (callback) {
  34158. if (this._onBindObserver) {
  34159. this.onBindObservable.remove(this._onBindObserver);
  34160. }
  34161. this._onBindObserver = this.onBindObservable.add(callback);
  34162. },
  34163. enumerable: true,
  34164. configurable: true
  34165. });
  34166. Object.defineProperty(Material.prototype, "alphaMode", {
  34167. /**
  34168. * Gets the value of the alpha mode
  34169. */
  34170. get: function () {
  34171. return this._alphaMode;
  34172. },
  34173. /**
  34174. * Sets the value of the alpha mode.
  34175. *
  34176. * | Value | Type | Description |
  34177. * | --- | --- | --- |
  34178. * | 0 | ALPHA_DISABLE | |
  34179. * | 1 | ALPHA_ADD | |
  34180. * | 2 | ALPHA_COMBINE | |
  34181. * | 3 | ALPHA_SUBTRACT | |
  34182. * | 4 | ALPHA_MULTIPLY | |
  34183. * | 5 | ALPHA_MAXIMIZED | |
  34184. * | 6 | ALPHA_ONEONE | |
  34185. * | 7 | ALPHA_PREMULTIPLIED | |
  34186. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34187. * | 9 | ALPHA_INTERPOLATE | |
  34188. * | 10 | ALPHA_SCREENMODE | |
  34189. *
  34190. */
  34191. set: function (value) {
  34192. if (this._alphaMode === value) {
  34193. return;
  34194. }
  34195. this._alphaMode = value;
  34196. this.markAsDirty(Material.TextureDirtyFlag);
  34197. },
  34198. enumerable: true,
  34199. configurable: true
  34200. });
  34201. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34202. /**
  34203. * Gets the depth pre-pass value
  34204. */
  34205. get: function () {
  34206. return this._needDepthPrePass;
  34207. },
  34208. /**
  34209. * Sets the need depth pre-pass value
  34210. */
  34211. set: function (value) {
  34212. if (this._needDepthPrePass === value) {
  34213. return;
  34214. }
  34215. this._needDepthPrePass = value;
  34216. if (this._needDepthPrePass) {
  34217. this.checkReadyOnEveryCall = true;
  34218. }
  34219. },
  34220. enumerable: true,
  34221. configurable: true
  34222. });
  34223. Object.defineProperty(Material.prototype, "fogEnabled", {
  34224. /**
  34225. * Gets the value of the fog enabled state
  34226. */
  34227. get: function () {
  34228. return this._fogEnabled;
  34229. },
  34230. /**
  34231. * Sets the state for enabling fog
  34232. */
  34233. set: function (value) {
  34234. if (this._fogEnabled === value) {
  34235. return;
  34236. }
  34237. this._fogEnabled = value;
  34238. this.markAsDirty(Material.MiscDirtyFlag);
  34239. },
  34240. enumerable: true,
  34241. configurable: true
  34242. });
  34243. Object.defineProperty(Material.prototype, "wireframe", {
  34244. /**
  34245. * Gets a value specifying if wireframe mode is enabled
  34246. */
  34247. get: function () {
  34248. switch (this._fillMode) {
  34249. case Material.WireFrameFillMode:
  34250. case Material.LineListDrawMode:
  34251. case Material.LineLoopDrawMode:
  34252. case Material.LineStripDrawMode:
  34253. return true;
  34254. }
  34255. return this._scene.forceWireframe;
  34256. },
  34257. /**
  34258. * Sets the state of wireframe mode
  34259. */
  34260. set: function (value) {
  34261. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34262. },
  34263. enumerable: true,
  34264. configurable: true
  34265. });
  34266. Object.defineProperty(Material.prototype, "pointsCloud", {
  34267. /**
  34268. * Gets the value specifying if point clouds are enabled
  34269. */
  34270. get: function () {
  34271. switch (this._fillMode) {
  34272. case Material.PointFillMode:
  34273. case Material.PointListDrawMode:
  34274. return true;
  34275. }
  34276. return this._scene.forcePointsCloud;
  34277. },
  34278. /**
  34279. * Sets the state of point cloud mode
  34280. */
  34281. set: function (value) {
  34282. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34283. },
  34284. enumerable: true,
  34285. configurable: true
  34286. });
  34287. Object.defineProperty(Material.prototype, "fillMode", {
  34288. /**
  34289. * Gets the material fill mode
  34290. */
  34291. get: function () {
  34292. return this._fillMode;
  34293. },
  34294. /**
  34295. * Sets the material fill mode
  34296. */
  34297. set: function (value) {
  34298. if (this._fillMode === value) {
  34299. return;
  34300. }
  34301. this._fillMode = value;
  34302. this.markAsDirty(Material.MiscDirtyFlag);
  34303. },
  34304. enumerable: true,
  34305. configurable: true
  34306. });
  34307. /**
  34308. * Returns a string representation of the current material
  34309. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34310. * @returns a string with material information
  34311. */
  34312. Material.prototype.toString = function (fullDetails) {
  34313. var ret = "Name: " + this.name;
  34314. if (fullDetails) {
  34315. }
  34316. return ret;
  34317. };
  34318. /**
  34319. * Gets the class name of the material
  34320. * @returns a string with the class name of the material
  34321. */
  34322. Material.prototype.getClassName = function () {
  34323. return "Material";
  34324. };
  34325. Object.defineProperty(Material.prototype, "isFrozen", {
  34326. /**
  34327. * Specifies if updates for the material been locked
  34328. */
  34329. get: function () {
  34330. return this.checkReadyOnlyOnce;
  34331. },
  34332. enumerable: true,
  34333. configurable: true
  34334. });
  34335. /**
  34336. * Locks updates for the material
  34337. */
  34338. Material.prototype.freeze = function () {
  34339. this.checkReadyOnlyOnce = true;
  34340. };
  34341. /**
  34342. * Unlocks updates for the material
  34343. */
  34344. Material.prototype.unfreeze = function () {
  34345. this.checkReadyOnlyOnce = false;
  34346. };
  34347. /**
  34348. * Specifies if the material is ready to be used
  34349. * @param mesh defines the mesh to check
  34350. * @param useInstances specifies if instances should be used
  34351. * @returns a boolean indicating if the material is ready to be used
  34352. */
  34353. Material.prototype.isReady = function (mesh, useInstances) {
  34354. return true;
  34355. };
  34356. /**
  34357. * Specifies that the submesh is ready to be used
  34358. * @param mesh defines the mesh to check
  34359. * @param subMesh defines which submesh to check
  34360. * @param useInstances specifies that instances should be used
  34361. * @returns a boolean indicating that the submesh is ready or not
  34362. */
  34363. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34364. return false;
  34365. };
  34366. /**
  34367. * Returns the material effect
  34368. * @returns the effect associated with the material
  34369. */
  34370. Material.prototype.getEffect = function () {
  34371. return this._effect;
  34372. };
  34373. /**
  34374. * Returns the current scene
  34375. * @returns a Scene
  34376. */
  34377. Material.prototype.getScene = function () {
  34378. return this._scene;
  34379. };
  34380. /**
  34381. * Specifies if the material will require alpha blending
  34382. * @returns a boolean specifying if alpha blending is needed
  34383. */
  34384. Material.prototype.needAlphaBlending = function () {
  34385. return (this.alpha < 1.0);
  34386. };
  34387. /**
  34388. * Specifies if the mesh will require alpha blending
  34389. * @param mesh defines the mesh to check
  34390. * @returns a boolean specifying if alpha blending is needed for the mesh
  34391. */
  34392. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34393. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34394. };
  34395. /**
  34396. * Specifies if this material should be rendered in alpha test mode
  34397. * @returns a boolean specifying if an alpha test is needed.
  34398. */
  34399. Material.prototype.needAlphaTesting = function () {
  34400. return false;
  34401. };
  34402. /**
  34403. * Gets the texture used for the alpha test
  34404. * @returns the texture to use for alpha testing
  34405. */
  34406. Material.prototype.getAlphaTestTexture = function () {
  34407. return null;
  34408. };
  34409. /**
  34410. * Marks the material to indicate that it needs to be re-calculated
  34411. */
  34412. Material.prototype.markDirty = function () {
  34413. this._wasPreviouslyReady = false;
  34414. };
  34415. /** @ignore */
  34416. Material.prototype._preBind = function (effect, overrideOrientation) {
  34417. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34418. var engine = this._scene.getEngine();
  34419. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34420. var reverse = orientation === Material.ClockWiseSideOrientation;
  34421. engine.enableEffect(effect ? effect : this._effect);
  34422. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34423. return reverse;
  34424. };
  34425. /**
  34426. * Binds the material to the mesh
  34427. * @param world defines the world transformation matrix
  34428. * @param mesh defines the mesh to bind the material to
  34429. */
  34430. Material.prototype.bind = function (world, mesh) {
  34431. };
  34432. /**
  34433. * Binds the submesh to the material
  34434. * @param world defines the world transformation matrix
  34435. * @param mesh defines the mesh containing the submesh
  34436. * @param subMesh defines the submesh to bind the material to
  34437. */
  34438. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34439. };
  34440. /**
  34441. * Binds the world matrix to the material
  34442. * @param world defines the world transformation matrix
  34443. */
  34444. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34445. };
  34446. /**
  34447. * Binds the scene's uniform buffer to the effect.
  34448. * @param effect defines the effect to bind to the scene uniform buffer
  34449. * @param sceneUbo defines the uniform buffer storing scene data
  34450. */
  34451. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34452. sceneUbo.bindToEffect(effect, "Scene");
  34453. };
  34454. /**
  34455. * Binds the view matrix to the effect
  34456. * @param effect defines the effect to bind the view matrix to
  34457. */
  34458. Material.prototype.bindView = function (effect) {
  34459. if (!this._useUBO) {
  34460. effect.setMatrix("view", this.getScene().getViewMatrix());
  34461. }
  34462. else {
  34463. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34464. }
  34465. };
  34466. /**
  34467. * Binds the view projection matrix to the effect
  34468. * @param effect defines the effect to bind the view projection matrix to
  34469. */
  34470. Material.prototype.bindViewProjection = function (effect) {
  34471. if (!this._useUBO) {
  34472. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34473. }
  34474. else {
  34475. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34476. }
  34477. };
  34478. /**
  34479. * Specifies if material alpha testing should be turned on for the mesh
  34480. * @param mesh defines the mesh to check
  34481. */
  34482. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34483. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34484. };
  34485. /**
  34486. * Processes to execute after binding the material to a mesh
  34487. * @param mesh defines the rendered mesh
  34488. */
  34489. Material.prototype._afterBind = function (mesh) {
  34490. this._scene._cachedMaterial = this;
  34491. if (mesh) {
  34492. this._scene._cachedVisibility = mesh.visibility;
  34493. }
  34494. else {
  34495. this._scene._cachedVisibility = 1;
  34496. }
  34497. if (mesh) {
  34498. this.onBindObservable.notifyObservers(mesh);
  34499. }
  34500. if (this.disableDepthWrite) {
  34501. var engine = this._scene.getEngine();
  34502. this._cachedDepthWriteState = engine.getDepthWrite();
  34503. engine.setDepthWrite(false);
  34504. }
  34505. };
  34506. /**
  34507. * Unbinds the material from the mesh
  34508. */
  34509. Material.prototype.unbind = function () {
  34510. this.onUnBindObservable.notifyObservers(this);
  34511. if (this.disableDepthWrite) {
  34512. var engine = this._scene.getEngine();
  34513. engine.setDepthWrite(this._cachedDepthWriteState);
  34514. }
  34515. };
  34516. /**
  34517. * Gets the active textures from the material
  34518. * @returns an array of textures
  34519. */
  34520. Material.prototype.getActiveTextures = function () {
  34521. return [];
  34522. };
  34523. /**
  34524. * Specifies if the material uses a texture
  34525. * @param texture defines the texture to check against the material
  34526. * @returns a boolean specifying if the material uses the texture
  34527. */
  34528. Material.prototype.hasTexture = function (texture) {
  34529. return false;
  34530. };
  34531. /**
  34532. * Makes a duplicate of the material, and gives it a new name
  34533. * @param name defines the new name for the duplicated material
  34534. * @returns the cloned material
  34535. */
  34536. Material.prototype.clone = function (name) {
  34537. return null;
  34538. };
  34539. /**
  34540. * Gets the meshes bound to the material
  34541. * @returns an array of meshes bound to the material
  34542. */
  34543. Material.prototype.getBindedMeshes = function () {
  34544. var result = new Array();
  34545. for (var index = 0; index < this._scene.meshes.length; index++) {
  34546. var mesh = this._scene.meshes[index];
  34547. if (mesh.material === this) {
  34548. result.push(mesh);
  34549. }
  34550. }
  34551. return result;
  34552. };
  34553. /**
  34554. * Force shader compilation
  34555. * @param mesh defines the mesh associated with this material
  34556. * @param onCompiled defines a function to execute once the material is compiled
  34557. * @param options defines the options to configure the compilation
  34558. */
  34559. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34560. var _this = this;
  34561. var localOptions = __assign({ clipPlane: false }, options);
  34562. var subMesh = new BABYLON.BaseSubMesh();
  34563. var scene = this.getScene();
  34564. var checkReady = function () {
  34565. if (!_this._scene || !_this._scene.getEngine()) {
  34566. return;
  34567. }
  34568. if (subMesh._materialDefines) {
  34569. subMesh._materialDefines._renderId = -1;
  34570. }
  34571. var clipPlaneState = scene.clipPlane;
  34572. if (localOptions.clipPlane) {
  34573. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34574. }
  34575. if (_this.storeEffectOnSubMeshes) {
  34576. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34577. if (onCompiled) {
  34578. onCompiled(_this);
  34579. }
  34580. }
  34581. else {
  34582. setTimeout(checkReady, 16);
  34583. }
  34584. }
  34585. else {
  34586. if (_this.isReady(mesh)) {
  34587. if (onCompiled) {
  34588. onCompiled(_this);
  34589. }
  34590. }
  34591. else {
  34592. setTimeout(checkReady, 16);
  34593. }
  34594. }
  34595. if (localOptions.clipPlane) {
  34596. scene.clipPlane = clipPlaneState;
  34597. }
  34598. };
  34599. checkReady();
  34600. };
  34601. /**
  34602. * Force shader compilation
  34603. * @param mesh defines the mesh that will use this material
  34604. * @param options defines additional options for compiling the shaders
  34605. * @returns a promise that resolves when the compilation completes
  34606. */
  34607. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34608. var _this = this;
  34609. return new Promise(function (resolve) {
  34610. _this.forceCompilation(mesh, function () {
  34611. resolve();
  34612. }, options);
  34613. });
  34614. };
  34615. /**
  34616. * Marks a define in the material to indicate that it needs to be re-computed
  34617. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34618. */
  34619. Material.prototype.markAsDirty = function (flag) {
  34620. if (flag & Material.TextureDirtyFlag) {
  34621. this._markAllSubMeshesAsTexturesDirty();
  34622. }
  34623. if (flag & Material.LightDirtyFlag) {
  34624. this._markAllSubMeshesAsLightsDirty();
  34625. }
  34626. if (flag & Material.FresnelDirtyFlag) {
  34627. this._markAllSubMeshesAsFresnelDirty();
  34628. }
  34629. if (flag & Material.AttributesDirtyFlag) {
  34630. this._markAllSubMeshesAsAttributesDirty();
  34631. }
  34632. if (flag & Material.MiscDirtyFlag) {
  34633. this._markAllSubMeshesAsMiscDirty();
  34634. }
  34635. this.getScene().resetCachedMaterial();
  34636. };
  34637. /**
  34638. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34639. * @param func defines a function which checks material defines against the submeshes
  34640. */
  34641. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34642. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34643. var mesh = _a[_i];
  34644. if (!mesh.subMeshes) {
  34645. continue;
  34646. }
  34647. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34648. var subMesh = _c[_b];
  34649. if (subMesh.getMaterial() !== this) {
  34650. continue;
  34651. }
  34652. if (!subMesh._materialDefines) {
  34653. continue;
  34654. }
  34655. func(subMesh._materialDefines);
  34656. }
  34657. }
  34658. };
  34659. /**
  34660. * Indicates that image processing needs to be re-calculated for all submeshes
  34661. */
  34662. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34663. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34664. };
  34665. /**
  34666. * Indicates that textures need to be re-calculated for all submeshes
  34667. */
  34668. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34669. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  34670. };
  34671. /**
  34672. * Indicates that fresnel needs to be re-calculated for all submeshes
  34673. */
  34674. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  34675. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  34676. };
  34677. /**
  34678. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  34679. */
  34680. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  34681. this._markAllSubMeshesAsDirty(function (defines) {
  34682. defines.markAsFresnelDirty();
  34683. defines.markAsMiscDirty();
  34684. });
  34685. };
  34686. /**
  34687. * Indicates that lights need to be re-calculated for all submeshes
  34688. */
  34689. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  34690. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  34691. };
  34692. /**
  34693. * Indicates that attributes need to be re-calculated for all submeshes
  34694. */
  34695. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  34696. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  34697. };
  34698. /**
  34699. * Indicates that misc needs to be re-calculated for all submeshes
  34700. */
  34701. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  34702. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  34703. };
  34704. /**
  34705. * Indicates that textures and misc need to be re-calculated for all submeshes
  34706. */
  34707. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  34708. this._markAllSubMeshesAsDirty(function (defines) {
  34709. defines.markAsTexturesDirty();
  34710. defines.markAsMiscDirty();
  34711. });
  34712. };
  34713. /**
  34714. * Disposes the material
  34715. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  34716. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  34717. */
  34718. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34719. // Animations
  34720. this.getScene().stopAnimation(this);
  34721. this.getScene().freeProcessedMaterials();
  34722. // Remove from scene
  34723. var index = this._scene.materials.indexOf(this);
  34724. if (index >= 0) {
  34725. this._scene.materials.splice(index, 1);
  34726. }
  34727. // Remove from meshes
  34728. for (index = 0; index < this._scene.meshes.length; index++) {
  34729. var mesh = this._scene.meshes[index];
  34730. if (mesh.material === this) {
  34731. mesh.material = null;
  34732. if (mesh.geometry) {
  34733. var geometry = (mesh.geometry);
  34734. if (this.storeEffectOnSubMeshes) {
  34735. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  34736. var subMesh = _a[_i];
  34737. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  34738. if (forceDisposeEffect && subMesh._materialEffect) {
  34739. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  34740. }
  34741. }
  34742. }
  34743. else {
  34744. geometry._releaseVertexArrayObject(this._effect);
  34745. }
  34746. }
  34747. }
  34748. }
  34749. this._uniformBuffer.dispose();
  34750. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  34751. if (forceDisposeEffect && this._effect) {
  34752. if (!this.storeEffectOnSubMeshes) {
  34753. this._scene.getEngine()._releaseEffect(this._effect);
  34754. }
  34755. this._effect = null;
  34756. }
  34757. // Callback
  34758. this.onDisposeObservable.notifyObservers(this);
  34759. this.onDisposeObservable.clear();
  34760. this.onBindObservable.clear();
  34761. this.onUnBindObservable.clear();
  34762. };
  34763. /**
  34764. * Serializes this material
  34765. * @returns the serialized material object
  34766. */
  34767. Material.prototype.serialize = function () {
  34768. return BABYLON.SerializationHelper.Serialize(this);
  34769. };
  34770. /**
  34771. * Creates a MultiMaterial from parsed MultiMaterial data.
  34772. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  34773. * @param scene defines the hosting scene
  34774. * @returns a new MultiMaterial
  34775. */
  34776. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  34777. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  34778. multiMaterial.id = parsedMultiMaterial.id;
  34779. if (BABYLON.Tags) {
  34780. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  34781. }
  34782. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  34783. var subMatId = parsedMultiMaterial.materials[matIndex];
  34784. if (subMatId) {
  34785. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  34786. }
  34787. else {
  34788. multiMaterial.subMaterials.push(null);
  34789. }
  34790. }
  34791. return multiMaterial;
  34792. };
  34793. /**
  34794. * Creates a material from parsed material data
  34795. * @param parsedMaterial defines parsed material data
  34796. * @param scene defines the hosting scene
  34797. * @param rootUrl defines the root URL to use to load textures
  34798. * @returns a new material
  34799. */
  34800. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  34801. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  34802. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  34803. }
  34804. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  34805. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  34806. if (!BABYLON.LegacyPBRMaterial) {
  34807. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  34808. return;
  34809. }
  34810. }
  34811. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  34812. return materialType.Parse(parsedMaterial, scene, rootUrl);
  34813. ;
  34814. };
  34815. // Triangle views
  34816. Material._TriangleFillMode = 0;
  34817. Material._WireFrameFillMode = 1;
  34818. Material._PointFillMode = 2;
  34819. // Draw modes
  34820. Material._PointListDrawMode = 3;
  34821. Material._LineListDrawMode = 4;
  34822. Material._LineLoopDrawMode = 5;
  34823. Material._LineStripDrawMode = 6;
  34824. Material._TriangleStripDrawMode = 7;
  34825. Material._TriangleFanDrawMode = 8;
  34826. /**
  34827. * Stores the clock-wise side orientation
  34828. */
  34829. Material._ClockWiseSideOrientation = 0;
  34830. /**
  34831. * Stores the counter clock-wise side orientation
  34832. */
  34833. Material._CounterClockWiseSideOrientation = 1;
  34834. /**
  34835. * The dirty texture flag value
  34836. */
  34837. Material._TextureDirtyFlag = 1;
  34838. /**
  34839. * The dirty light flag value
  34840. */
  34841. Material._LightDirtyFlag = 2;
  34842. /**
  34843. * The dirty fresnel flag value
  34844. */
  34845. Material._FresnelDirtyFlag = 4;
  34846. /**
  34847. * The dirty attribute flag value
  34848. */
  34849. Material._AttributesDirtyFlag = 8;
  34850. /**
  34851. * The dirty misc flag value
  34852. */
  34853. Material._MiscDirtyFlag = 16;
  34854. __decorate([
  34855. BABYLON.serialize()
  34856. ], Material.prototype, "id", void 0);
  34857. __decorate([
  34858. BABYLON.serialize()
  34859. ], Material.prototype, "name", void 0);
  34860. __decorate([
  34861. BABYLON.serialize()
  34862. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  34863. __decorate([
  34864. BABYLON.serialize()
  34865. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  34866. __decorate([
  34867. BABYLON.serialize()
  34868. ], Material.prototype, "state", void 0);
  34869. __decorate([
  34870. BABYLON.serialize("alpha")
  34871. ], Material.prototype, "_alpha", void 0);
  34872. __decorate([
  34873. BABYLON.serialize("backFaceCulling")
  34874. ], Material.prototype, "_backFaceCulling", void 0);
  34875. __decorate([
  34876. BABYLON.serialize()
  34877. ], Material.prototype, "sideOrientation", void 0);
  34878. __decorate([
  34879. BABYLON.serialize("alphaMode")
  34880. ], Material.prototype, "_alphaMode", void 0);
  34881. __decorate([
  34882. BABYLON.serialize()
  34883. ], Material.prototype, "_needDepthPrePass", void 0);
  34884. __decorate([
  34885. BABYLON.serialize()
  34886. ], Material.prototype, "disableDepthWrite", void 0);
  34887. __decorate([
  34888. BABYLON.serialize()
  34889. ], Material.prototype, "forceDepthWrite", void 0);
  34890. __decorate([
  34891. BABYLON.serialize()
  34892. ], Material.prototype, "separateCullingPass", void 0);
  34893. __decorate([
  34894. BABYLON.serialize("fogEnabled")
  34895. ], Material.prototype, "_fogEnabled", void 0);
  34896. __decorate([
  34897. BABYLON.serialize()
  34898. ], Material.prototype, "pointSize", void 0);
  34899. __decorate([
  34900. BABYLON.serialize()
  34901. ], Material.prototype, "zOffset", void 0);
  34902. __decorate([
  34903. BABYLON.serialize()
  34904. ], Material.prototype, "wireframe", null);
  34905. __decorate([
  34906. BABYLON.serialize()
  34907. ], Material.prototype, "pointsCloud", null);
  34908. __decorate([
  34909. BABYLON.serialize()
  34910. ], Material.prototype, "fillMode", null);
  34911. return Material;
  34912. }());
  34913. BABYLON.Material = Material;
  34914. })(BABYLON || (BABYLON = {}));
  34915. //# sourceMappingURL=babylon.material.js.map
  34916. "use strict";
  34917. var BABYLON;
  34918. (function (BABYLON) {
  34919. var UniformBuffer = /** @class */ (function () {
  34920. /**
  34921. * Uniform buffer objects.
  34922. *
  34923. * Handles blocks of uniform on the GPU.
  34924. *
  34925. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  34926. *
  34927. * For more information, please refer to :
  34928. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  34929. */
  34930. function UniformBuffer(engine, data, dynamic) {
  34931. this._engine = engine;
  34932. this._noUBO = !engine.supportsUniformBuffers;
  34933. this._dynamic = dynamic;
  34934. this._data = data || [];
  34935. this._uniformLocations = {};
  34936. this._uniformSizes = {};
  34937. this._uniformLocationPointer = 0;
  34938. this._needSync = false;
  34939. if (this._noUBO) {
  34940. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  34941. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  34942. this.updateFloat = this._updateFloatForEffect;
  34943. this.updateFloat2 = this._updateFloat2ForEffect;
  34944. this.updateFloat3 = this._updateFloat3ForEffect;
  34945. this.updateFloat4 = this._updateFloat4ForEffect;
  34946. this.updateMatrix = this._updateMatrixForEffect;
  34947. this.updateVector3 = this._updateVector3ForEffect;
  34948. this.updateVector4 = this._updateVector4ForEffect;
  34949. this.updateColor3 = this._updateColor3ForEffect;
  34950. this.updateColor4 = this._updateColor4ForEffect;
  34951. }
  34952. else {
  34953. this._engine._uniformBuffers.push(this);
  34954. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  34955. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  34956. this.updateFloat = this._updateFloatForUniform;
  34957. this.updateFloat2 = this._updateFloat2ForUniform;
  34958. this.updateFloat3 = this._updateFloat3ForUniform;
  34959. this.updateFloat4 = this._updateFloat4ForUniform;
  34960. this.updateMatrix = this._updateMatrixForUniform;
  34961. this.updateVector3 = this._updateVector3ForUniform;
  34962. this.updateVector4 = this._updateVector4ForUniform;
  34963. this.updateColor3 = this._updateColor3ForUniform;
  34964. this.updateColor4 = this._updateColor4ForUniform;
  34965. }
  34966. }
  34967. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  34968. // Properties
  34969. /**
  34970. * Indicates if the buffer is using the WebGL2 UBO implementation,
  34971. * or just falling back on setUniformXXX calls.
  34972. */
  34973. get: function () {
  34974. return !this._noUBO;
  34975. },
  34976. enumerable: true,
  34977. configurable: true
  34978. });
  34979. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  34980. /**
  34981. * Indicates if the WebGL underlying uniform buffer is in sync
  34982. * with the javascript cache data.
  34983. */
  34984. get: function () {
  34985. return !this._needSync;
  34986. },
  34987. enumerable: true,
  34988. configurable: true
  34989. });
  34990. /**
  34991. * Indicates if the WebGL underlying uniform buffer is dynamic.
  34992. * Also, a dynamic UniformBuffer will disable cache verification and always
  34993. * update the underlying WebGL uniform buffer to the GPU.
  34994. */
  34995. UniformBuffer.prototype.isDynamic = function () {
  34996. return this._dynamic !== undefined;
  34997. };
  34998. /**
  34999. * The data cache on JS side.
  35000. */
  35001. UniformBuffer.prototype.getData = function () {
  35002. return this._bufferData;
  35003. };
  35004. /**
  35005. * The underlying WebGL Uniform buffer.
  35006. */
  35007. UniformBuffer.prototype.getBuffer = function () {
  35008. return this._buffer;
  35009. };
  35010. /**
  35011. * std140 layout specifies how to align data within an UBO structure.
  35012. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35013. * for specs.
  35014. */
  35015. UniformBuffer.prototype._fillAlignment = function (size) {
  35016. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35017. // and 4x4 matrices
  35018. // TODO : change if other types are used
  35019. var alignment;
  35020. if (size <= 2) {
  35021. alignment = size;
  35022. }
  35023. else {
  35024. alignment = 4;
  35025. }
  35026. if ((this._uniformLocationPointer % alignment) !== 0) {
  35027. var oldPointer = this._uniformLocationPointer;
  35028. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35029. var diff = this._uniformLocationPointer - oldPointer;
  35030. for (var i = 0; i < diff; i++) {
  35031. this._data.push(0);
  35032. }
  35033. }
  35034. };
  35035. /**
  35036. * Adds an uniform in the buffer.
  35037. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35038. * for the layout to be correct !
  35039. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35040. * @param {number|number[]} size Data size, or data directly.
  35041. */
  35042. UniformBuffer.prototype.addUniform = function (name, size) {
  35043. if (this._noUBO) {
  35044. return;
  35045. }
  35046. if (this._uniformLocations[name] !== undefined) {
  35047. // Already existing uniform
  35048. return;
  35049. }
  35050. // This function must be called in the order of the shader layout !
  35051. // size can be the size of the uniform, or data directly
  35052. var data;
  35053. if (size instanceof Array) {
  35054. data = size;
  35055. size = data.length;
  35056. }
  35057. else {
  35058. size = size;
  35059. data = [];
  35060. // Fill with zeros
  35061. for (var i = 0; i < size; i++) {
  35062. data.push(0);
  35063. }
  35064. }
  35065. this._fillAlignment(size);
  35066. this._uniformSizes[name] = size;
  35067. this._uniformLocations[name] = this._uniformLocationPointer;
  35068. this._uniformLocationPointer += size;
  35069. for (var i = 0; i < size; i++) {
  35070. this._data.push(data[i]);
  35071. }
  35072. this._needSync = true;
  35073. };
  35074. /**
  35075. * Wrapper for addUniform.
  35076. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35077. * @param {Matrix} mat A 4x4 matrix.
  35078. */
  35079. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35080. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35081. };
  35082. /**
  35083. * Wrapper for addUniform.
  35084. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35085. * @param {number} x
  35086. * @param {number} y
  35087. */
  35088. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35089. var temp = [x, y];
  35090. this.addUniform(name, temp);
  35091. };
  35092. /**
  35093. * Wrapper for addUniform.
  35094. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35095. * @param {number} x
  35096. * @param {number} y
  35097. * @param {number} z
  35098. */
  35099. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35100. var temp = [x, y, z];
  35101. this.addUniform(name, temp);
  35102. };
  35103. /**
  35104. * Wrapper for addUniform.
  35105. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35106. * @param {Color3} color
  35107. */
  35108. UniformBuffer.prototype.addColor3 = function (name, color) {
  35109. var temp = new Array();
  35110. color.toArray(temp);
  35111. this.addUniform(name, temp);
  35112. };
  35113. /**
  35114. * Wrapper for addUniform.
  35115. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35116. * @param {Color3} color
  35117. * @param {number} alpha
  35118. */
  35119. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35120. var temp = new Array();
  35121. color.toArray(temp);
  35122. temp.push(alpha);
  35123. this.addUniform(name, temp);
  35124. };
  35125. /**
  35126. * Wrapper for addUniform.
  35127. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35128. * @param {Vector3} vector
  35129. */
  35130. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35131. var temp = new Array();
  35132. vector.toArray(temp);
  35133. this.addUniform(name, temp);
  35134. };
  35135. /**
  35136. * Wrapper for addUniform.
  35137. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35138. */
  35139. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35140. this.addUniform(name, 12);
  35141. };
  35142. /**
  35143. * Wrapper for addUniform.
  35144. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35145. */
  35146. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35147. this.addUniform(name, 8);
  35148. };
  35149. /**
  35150. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35151. */
  35152. UniformBuffer.prototype.create = function () {
  35153. if (this._noUBO) {
  35154. return;
  35155. }
  35156. if (this._buffer) {
  35157. return; // nothing to do
  35158. }
  35159. // See spec, alignment must be filled as a vec4
  35160. this._fillAlignment(4);
  35161. this._bufferData = new Float32Array(this._data);
  35162. this._rebuild();
  35163. this._needSync = true;
  35164. };
  35165. UniformBuffer.prototype._rebuild = function () {
  35166. if (this._noUBO) {
  35167. return;
  35168. }
  35169. if (this._dynamic) {
  35170. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35171. }
  35172. else {
  35173. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35174. }
  35175. };
  35176. /**
  35177. * Updates the WebGL Uniform Buffer on the GPU.
  35178. * If the `dynamic` flag is set to true, no cache comparison is done.
  35179. * Otherwise, the buffer will be updated only if the cache differs.
  35180. */
  35181. UniformBuffer.prototype.update = function () {
  35182. if (!this._buffer) {
  35183. this.create();
  35184. return;
  35185. }
  35186. if (!this._dynamic && !this._needSync) {
  35187. return;
  35188. }
  35189. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35190. this._needSync = false;
  35191. };
  35192. /**
  35193. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35194. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35195. * @param {number[]|Float32Array} data Flattened data
  35196. * @param {number} size Size of the data.
  35197. */
  35198. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35199. var location = this._uniformLocations[uniformName];
  35200. if (location === undefined) {
  35201. if (this._buffer) {
  35202. // Cannot add an uniform if the buffer is already created
  35203. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35204. return;
  35205. }
  35206. this.addUniform(uniformName, size);
  35207. location = this._uniformLocations[uniformName];
  35208. }
  35209. if (!this._buffer) {
  35210. this.create();
  35211. }
  35212. if (!this._dynamic) {
  35213. // Cache for static uniform buffers
  35214. var changed = false;
  35215. for (var i = 0; i < size; i++) {
  35216. if (this._bufferData[location + i] !== data[i]) {
  35217. changed = true;
  35218. this._bufferData[location + i] = data[i];
  35219. }
  35220. }
  35221. this._needSync = this._needSync || changed;
  35222. }
  35223. else {
  35224. // No cache for dynamic
  35225. for (var i = 0; i < size; i++) {
  35226. this._bufferData[location + i] = data[i];
  35227. }
  35228. }
  35229. };
  35230. // Update methods
  35231. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35232. // To match std140, matrix must be realigned
  35233. for (var i = 0; i < 3; i++) {
  35234. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35235. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35236. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35237. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35238. }
  35239. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35240. };
  35241. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35242. this._currentEffect.setMatrix3x3(name, matrix);
  35243. };
  35244. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35245. this._currentEffect.setMatrix2x2(name, matrix);
  35246. };
  35247. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35248. // To match std140, matrix must be realigned
  35249. for (var i = 0; i < 2; i++) {
  35250. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35251. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35252. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35253. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35254. }
  35255. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35256. };
  35257. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35258. this._currentEffect.setFloat(name, x);
  35259. };
  35260. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35261. UniformBuffer._tempBuffer[0] = x;
  35262. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35263. };
  35264. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35265. if (suffix === void 0) { suffix = ""; }
  35266. this._currentEffect.setFloat2(name + suffix, x, y);
  35267. };
  35268. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35269. if (suffix === void 0) { suffix = ""; }
  35270. UniformBuffer._tempBuffer[0] = x;
  35271. UniformBuffer._tempBuffer[1] = y;
  35272. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35273. };
  35274. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35275. if (suffix === void 0) { suffix = ""; }
  35276. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35277. };
  35278. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35279. if (suffix === void 0) { suffix = ""; }
  35280. UniformBuffer._tempBuffer[0] = x;
  35281. UniformBuffer._tempBuffer[1] = y;
  35282. UniformBuffer._tempBuffer[2] = z;
  35283. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35284. };
  35285. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35286. if (suffix === void 0) { suffix = ""; }
  35287. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35288. };
  35289. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35290. if (suffix === void 0) { suffix = ""; }
  35291. UniformBuffer._tempBuffer[0] = x;
  35292. UniformBuffer._tempBuffer[1] = y;
  35293. UniformBuffer._tempBuffer[2] = z;
  35294. UniformBuffer._tempBuffer[3] = w;
  35295. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35296. };
  35297. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35298. this._currentEffect.setMatrix(name, mat);
  35299. };
  35300. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35301. this.updateUniform(name, mat.toArray(), 16);
  35302. };
  35303. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35304. this._currentEffect.setVector3(name, vector);
  35305. };
  35306. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35307. vector.toArray(UniformBuffer._tempBuffer);
  35308. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35309. };
  35310. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35311. this._currentEffect.setVector4(name, vector);
  35312. };
  35313. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35314. vector.toArray(UniformBuffer._tempBuffer);
  35315. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35316. };
  35317. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35318. if (suffix === void 0) { suffix = ""; }
  35319. this._currentEffect.setColor3(name + suffix, color);
  35320. };
  35321. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35322. if (suffix === void 0) { suffix = ""; }
  35323. color.toArray(UniformBuffer._tempBuffer);
  35324. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35325. };
  35326. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35327. if (suffix === void 0) { suffix = ""; }
  35328. this._currentEffect.setColor4(name + suffix, color, alpha);
  35329. };
  35330. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35331. if (suffix === void 0) { suffix = ""; }
  35332. color.toArray(UniformBuffer._tempBuffer);
  35333. UniformBuffer._tempBuffer[3] = alpha;
  35334. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35335. };
  35336. /**
  35337. * Sets a sampler uniform on the effect.
  35338. * @param {string} name Name of the sampler.
  35339. * @param {Texture} texture
  35340. */
  35341. UniformBuffer.prototype.setTexture = function (name, texture) {
  35342. this._currentEffect.setTexture(name, texture);
  35343. };
  35344. /**
  35345. * Directly updates the value of the uniform in the cache AND on the GPU.
  35346. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35347. * @param {number[]|Float32Array} data Flattened data
  35348. */
  35349. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35350. this.updateUniform(uniformName, data, data.length);
  35351. this.update();
  35352. };
  35353. /**
  35354. * Binds this uniform buffer to an effect.
  35355. * @param {Effect} effect
  35356. * @param {string} name Name of the uniform block in the shader.
  35357. */
  35358. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35359. this._currentEffect = effect;
  35360. if (this._noUBO || !this._buffer) {
  35361. return;
  35362. }
  35363. effect.bindUniformBuffer(this._buffer, name);
  35364. };
  35365. /**
  35366. * Disposes the uniform buffer.
  35367. */
  35368. UniformBuffer.prototype.dispose = function () {
  35369. if (this._noUBO) {
  35370. return;
  35371. }
  35372. var index = this._engine._uniformBuffers.indexOf(this);
  35373. if (index !== -1) {
  35374. this._engine._uniformBuffers.splice(index, 1);
  35375. }
  35376. if (!this._buffer) {
  35377. return;
  35378. }
  35379. if (this._engine._releaseBuffer(this._buffer)) {
  35380. this._buffer = null;
  35381. }
  35382. };
  35383. // Pool for avoiding memory leaks
  35384. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35385. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35386. return UniformBuffer;
  35387. }());
  35388. BABYLON.UniformBuffer = UniformBuffer;
  35389. })(BABYLON || (BABYLON = {}));
  35390. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35391. "use strict";
  35392. var BABYLON;
  35393. (function (BABYLON) {
  35394. var VertexData = /** @class */ (function () {
  35395. function VertexData() {
  35396. }
  35397. VertexData.prototype.set = function (data, kind) {
  35398. switch (kind) {
  35399. case BABYLON.VertexBuffer.PositionKind:
  35400. this.positions = data;
  35401. break;
  35402. case BABYLON.VertexBuffer.NormalKind:
  35403. this.normals = data;
  35404. break;
  35405. case BABYLON.VertexBuffer.TangentKind:
  35406. this.tangents = data;
  35407. break;
  35408. case BABYLON.VertexBuffer.UVKind:
  35409. this.uvs = data;
  35410. break;
  35411. case BABYLON.VertexBuffer.UV2Kind:
  35412. this.uvs2 = data;
  35413. break;
  35414. case BABYLON.VertexBuffer.UV3Kind:
  35415. this.uvs3 = data;
  35416. break;
  35417. case BABYLON.VertexBuffer.UV4Kind:
  35418. this.uvs4 = data;
  35419. break;
  35420. case BABYLON.VertexBuffer.UV5Kind:
  35421. this.uvs5 = data;
  35422. break;
  35423. case BABYLON.VertexBuffer.UV6Kind:
  35424. this.uvs6 = data;
  35425. break;
  35426. case BABYLON.VertexBuffer.ColorKind:
  35427. this.colors = data;
  35428. break;
  35429. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35430. this.matricesIndices = data;
  35431. break;
  35432. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35433. this.matricesWeights = data;
  35434. break;
  35435. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35436. this.matricesIndicesExtra = data;
  35437. break;
  35438. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35439. this.matricesWeightsExtra = data;
  35440. break;
  35441. }
  35442. };
  35443. /**
  35444. * Associates the vertexData to the passed Mesh.
  35445. * Sets it as updatable or not (default `false`).
  35446. * Returns the VertexData.
  35447. */
  35448. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35449. this._applyTo(mesh, updatable);
  35450. return this;
  35451. };
  35452. /**
  35453. * Associates the vertexData to the passed Geometry.
  35454. * Sets it as updatable or not (default `false`).
  35455. * Returns the VertexData.
  35456. */
  35457. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35458. this._applyTo(geometry, updatable);
  35459. return this;
  35460. };
  35461. /**
  35462. * Updates the associated mesh.
  35463. * Returns the VertexData.
  35464. */
  35465. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35466. this._update(mesh);
  35467. return this;
  35468. };
  35469. /**
  35470. * Updates the associated geometry.
  35471. * Returns the VertexData.
  35472. */
  35473. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35474. this._update(geometry);
  35475. return this;
  35476. };
  35477. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35478. if (updatable === void 0) { updatable = false; }
  35479. if (this.positions) {
  35480. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35481. }
  35482. if (this.normals) {
  35483. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35484. }
  35485. if (this.tangents) {
  35486. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35487. }
  35488. if (this.uvs) {
  35489. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35490. }
  35491. if (this.uvs2) {
  35492. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35493. }
  35494. if (this.uvs3) {
  35495. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35496. }
  35497. if (this.uvs4) {
  35498. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35499. }
  35500. if (this.uvs5) {
  35501. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35502. }
  35503. if (this.uvs6) {
  35504. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35505. }
  35506. if (this.colors) {
  35507. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35508. }
  35509. if (this.matricesIndices) {
  35510. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35511. }
  35512. if (this.matricesWeights) {
  35513. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35514. }
  35515. if (this.matricesIndicesExtra) {
  35516. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35517. }
  35518. if (this.matricesWeightsExtra) {
  35519. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35520. }
  35521. if (this.indices) {
  35522. meshOrGeometry.setIndices(this.indices, null, updatable);
  35523. }
  35524. return this;
  35525. };
  35526. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35527. if (this.positions) {
  35528. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35529. }
  35530. if (this.normals) {
  35531. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35532. }
  35533. if (this.tangents) {
  35534. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35535. }
  35536. if (this.uvs) {
  35537. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35538. }
  35539. if (this.uvs2) {
  35540. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35541. }
  35542. if (this.uvs3) {
  35543. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35544. }
  35545. if (this.uvs4) {
  35546. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35547. }
  35548. if (this.uvs5) {
  35549. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35550. }
  35551. if (this.uvs6) {
  35552. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35553. }
  35554. if (this.colors) {
  35555. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35556. }
  35557. if (this.matricesIndices) {
  35558. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35559. }
  35560. if (this.matricesWeights) {
  35561. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35562. }
  35563. if (this.matricesIndicesExtra) {
  35564. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35565. }
  35566. if (this.matricesWeightsExtra) {
  35567. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35568. }
  35569. if (this.indices) {
  35570. meshOrGeometry.setIndices(this.indices, null);
  35571. }
  35572. return this;
  35573. };
  35574. /**
  35575. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  35576. * Returns the VertexData.
  35577. */
  35578. VertexData.prototype.transform = function (matrix) {
  35579. var transformed = BABYLON.Vector3.Zero();
  35580. var index;
  35581. if (this.positions) {
  35582. var position = BABYLON.Vector3.Zero();
  35583. for (index = 0; index < this.positions.length; index += 3) {
  35584. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35585. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35586. this.positions[index] = transformed.x;
  35587. this.positions[index + 1] = transformed.y;
  35588. this.positions[index + 2] = transformed.z;
  35589. }
  35590. }
  35591. if (this.normals) {
  35592. var normal = BABYLON.Vector3.Zero();
  35593. for (index = 0; index < this.normals.length; index += 3) {
  35594. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35595. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35596. this.normals[index] = transformed.x;
  35597. this.normals[index + 1] = transformed.y;
  35598. this.normals[index + 2] = transformed.z;
  35599. }
  35600. }
  35601. if (this.tangents) {
  35602. var tangent = BABYLON.Vector4.Zero();
  35603. var tangentTransformed = BABYLON.Vector4.Zero();
  35604. for (index = 0; index < this.tangents.length; index += 4) {
  35605. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35606. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35607. this.tangents[index] = tangentTransformed.x;
  35608. this.tangents[index + 1] = tangentTransformed.y;
  35609. this.tangents[index + 2] = tangentTransformed.z;
  35610. this.tangents[index + 3] = tangentTransformed.w;
  35611. }
  35612. }
  35613. return this;
  35614. };
  35615. /**
  35616. * Merges the passed VertexData into the current one.
  35617. * Returns the modified VertexData.
  35618. */
  35619. VertexData.prototype.merge = function (other) {
  35620. this._validate();
  35621. other._validate();
  35622. if (!this.normals !== !other.normals ||
  35623. !this.tangents !== !other.tangents ||
  35624. !this.uvs !== !other.uvs ||
  35625. !this.uvs2 !== !other.uvs2 ||
  35626. !this.uvs3 !== !other.uvs3 ||
  35627. !this.uvs4 !== !other.uvs4 ||
  35628. !this.uvs5 !== !other.uvs5 ||
  35629. !this.uvs6 !== !other.uvs6 ||
  35630. !this.colors !== !other.colors ||
  35631. !this.matricesIndices !== !other.matricesIndices ||
  35632. !this.matricesWeights !== !other.matricesWeights ||
  35633. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35634. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35635. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35636. }
  35637. if (other.indices) {
  35638. if (!this.indices) {
  35639. this.indices = [];
  35640. }
  35641. var offset = this.positions ? this.positions.length / 3 : 0;
  35642. for (var index = 0; index < other.indices.length; index++) {
  35643. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35644. this.indices.push(other.indices[index] + offset);
  35645. }
  35646. }
  35647. this.positions = this._mergeElement(this.positions, other.positions);
  35648. this.normals = this._mergeElement(this.normals, other.normals);
  35649. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35650. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35651. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35652. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35653. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35654. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35655. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35656. this.colors = this._mergeElement(this.colors, other.colors);
  35657. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35658. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35659. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35660. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35661. return this;
  35662. };
  35663. VertexData.prototype._mergeElement = function (source, other) {
  35664. if (!source) {
  35665. return other;
  35666. }
  35667. if (!other) {
  35668. return source;
  35669. }
  35670. var len = other.length + source.length;
  35671. var isSrcTypedArray = source instanceof Float32Array;
  35672. var isOthTypedArray = other instanceof Float32Array;
  35673. // use non-loop method when the source is Float32Array
  35674. if (isSrcTypedArray) {
  35675. var ret32 = new Float32Array(len);
  35676. ret32.set(source);
  35677. ret32.set(other, source.length);
  35678. return ret32;
  35679. // source is number[], when other is also use concat
  35680. }
  35681. else if (!isOthTypedArray) {
  35682. return source.concat(other);
  35683. // source is a number[], but other is a Float32Array, loop required
  35684. }
  35685. else {
  35686. var ret = source.slice(0); // copy source to a separate array
  35687. for (var i = 0, len = other.length; i < len; i++) {
  35688. ret.push(other[i]);
  35689. }
  35690. return ret;
  35691. }
  35692. };
  35693. VertexData.prototype._validate = function () {
  35694. if (!this.positions) {
  35695. throw new Error("Positions are required");
  35696. }
  35697. var getElementCount = function (kind, values) {
  35698. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  35699. if ((values.length % stride) !== 0) {
  35700. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  35701. }
  35702. return values.length / stride;
  35703. };
  35704. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  35705. var validateElementCount = function (kind, values) {
  35706. var elementCount = getElementCount(kind, values);
  35707. if (elementCount !== positionsElementCount) {
  35708. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  35709. }
  35710. };
  35711. if (this.normals)
  35712. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  35713. if (this.tangents)
  35714. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  35715. if (this.uvs)
  35716. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  35717. if (this.uvs2)
  35718. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  35719. if (this.uvs3)
  35720. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  35721. if (this.uvs4)
  35722. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  35723. if (this.uvs5)
  35724. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  35725. if (this.uvs6)
  35726. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  35727. if (this.colors)
  35728. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  35729. if (this.matricesIndices)
  35730. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  35731. if (this.matricesWeights)
  35732. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  35733. if (this.matricesIndicesExtra)
  35734. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  35735. if (this.matricesWeightsExtra)
  35736. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  35737. };
  35738. /**
  35739. * Serializes the VertexData.
  35740. * Returns a serialized object.
  35741. */
  35742. VertexData.prototype.serialize = function () {
  35743. var serializationObject = this.serialize();
  35744. if (this.positions) {
  35745. serializationObject.positions = this.positions;
  35746. }
  35747. if (this.normals) {
  35748. serializationObject.normals = this.normals;
  35749. }
  35750. if (this.tangents) {
  35751. serializationObject.tangents = this.tangents;
  35752. }
  35753. if (this.uvs) {
  35754. serializationObject.uvs = this.uvs;
  35755. }
  35756. if (this.uvs2) {
  35757. serializationObject.uvs2 = this.uvs2;
  35758. }
  35759. if (this.uvs3) {
  35760. serializationObject.uvs3 = this.uvs3;
  35761. }
  35762. if (this.uvs4) {
  35763. serializationObject.uvs4 = this.uvs4;
  35764. }
  35765. if (this.uvs5) {
  35766. serializationObject.uvs5 = this.uvs5;
  35767. }
  35768. if (this.uvs6) {
  35769. serializationObject.uvs6 = this.uvs6;
  35770. }
  35771. if (this.colors) {
  35772. serializationObject.colors = this.colors;
  35773. }
  35774. if (this.matricesIndices) {
  35775. serializationObject.matricesIndices = this.matricesIndices;
  35776. serializationObject.matricesIndices._isExpanded = true;
  35777. }
  35778. if (this.matricesWeights) {
  35779. serializationObject.matricesWeights = this.matricesWeights;
  35780. }
  35781. if (this.matricesIndicesExtra) {
  35782. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  35783. serializationObject.matricesIndicesExtra._isExpanded = true;
  35784. }
  35785. if (this.matricesWeightsExtra) {
  35786. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  35787. }
  35788. serializationObject.indices = this.indices;
  35789. return serializationObject;
  35790. };
  35791. // Statics
  35792. /**
  35793. * Returns the object VertexData associated to the passed mesh.
  35794. */
  35795. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  35796. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  35797. };
  35798. /**
  35799. * Returns the object VertexData associated to the passed geometry.
  35800. */
  35801. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  35802. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  35803. };
  35804. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  35805. var result = new VertexData();
  35806. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35807. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  35808. }
  35809. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35810. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  35811. }
  35812. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35813. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  35814. }
  35815. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35816. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  35817. }
  35818. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35819. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  35820. }
  35821. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35822. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  35823. }
  35824. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35825. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  35826. }
  35827. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35828. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  35829. }
  35830. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35831. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  35832. }
  35833. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35834. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  35835. }
  35836. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35837. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  35838. }
  35839. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35840. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  35841. }
  35842. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  35843. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  35844. }
  35845. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  35846. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  35847. }
  35848. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  35849. return result;
  35850. };
  35851. /**
  35852. * Creates the vertexData of the Ribbon.
  35853. */
  35854. VertexData.CreateRibbon = function (options) {
  35855. var pathArray = options.pathArray;
  35856. var closeArray = options.closeArray || false;
  35857. var closePath = options.closePath || false;
  35858. var invertUV = options.invertUV || false;
  35859. var defaultOffset = Math.floor(pathArray[0].length / 2);
  35860. var offset = options.offset || defaultOffset;
  35861. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  35862. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35863. var customUV = options.uvs;
  35864. var customColors = options.colors;
  35865. var positions = [];
  35866. var indices = [];
  35867. var normals = [];
  35868. var uvs = [];
  35869. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  35870. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  35871. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  35872. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  35873. var minlg; // minimal length among all paths from pathArray
  35874. var lg = []; // array of path lengths : nb of vertex per path
  35875. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  35876. var p; // path iterator
  35877. var i; // point iterator
  35878. var j; // point iterator
  35879. // if single path in pathArray
  35880. if (pathArray.length < 2) {
  35881. var ar1 = [];
  35882. var ar2 = [];
  35883. for (i = 0; i < pathArray[0].length - offset; i++) {
  35884. ar1.push(pathArray[0][i]);
  35885. ar2.push(pathArray[0][i + offset]);
  35886. }
  35887. pathArray = [ar1, ar2];
  35888. }
  35889. // positions and horizontal distances (u)
  35890. var idc = 0;
  35891. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  35892. var path;
  35893. var l;
  35894. minlg = pathArray[0].length;
  35895. var vectlg;
  35896. var dist;
  35897. for (p = 0; p < pathArray.length; p++) {
  35898. uTotalDistance[p] = 0;
  35899. us[p] = [0];
  35900. path = pathArray[p];
  35901. l = path.length;
  35902. minlg = (minlg < l) ? minlg : l;
  35903. j = 0;
  35904. while (j < l) {
  35905. positions.push(path[j].x, path[j].y, path[j].z);
  35906. if (j > 0) {
  35907. vectlg = path[j].subtract(path[j - 1]).length();
  35908. dist = vectlg + uTotalDistance[p];
  35909. us[p].push(dist);
  35910. uTotalDistance[p] = dist;
  35911. }
  35912. j++;
  35913. }
  35914. if (closePath) {
  35915. j--;
  35916. positions.push(path[0].x, path[0].y, path[0].z);
  35917. vectlg = path[j].subtract(path[0]).length();
  35918. dist = vectlg + uTotalDistance[p];
  35919. us[p].push(dist);
  35920. uTotalDistance[p] = dist;
  35921. }
  35922. lg[p] = l + closePathCorr;
  35923. idx[p] = idc;
  35924. idc += (l + closePathCorr);
  35925. }
  35926. // vertical distances (v)
  35927. var path1;
  35928. var path2;
  35929. var vertex1 = null;
  35930. var vertex2 = null;
  35931. for (i = 0; i < minlg + closePathCorr; i++) {
  35932. vTotalDistance[i] = 0;
  35933. vs[i] = [0];
  35934. for (p = 0; p < pathArray.length - 1; p++) {
  35935. path1 = pathArray[p];
  35936. path2 = pathArray[p + 1];
  35937. if (i === minlg) {
  35938. vertex1 = path1[0];
  35939. vertex2 = path2[0];
  35940. }
  35941. else {
  35942. vertex1 = path1[i];
  35943. vertex2 = path2[i];
  35944. }
  35945. vectlg = vertex2.subtract(vertex1).length();
  35946. dist = vectlg + vTotalDistance[i];
  35947. vs[i].push(dist);
  35948. vTotalDistance[i] = dist;
  35949. }
  35950. if (closeArray && vertex2 && vertex1) {
  35951. path1 = pathArray[p];
  35952. path2 = pathArray[0];
  35953. if (i === minlg) {
  35954. vertex2 = path2[0];
  35955. }
  35956. vectlg = vertex2.subtract(vertex1).length();
  35957. dist = vectlg + vTotalDistance[i];
  35958. vTotalDistance[i] = dist;
  35959. }
  35960. }
  35961. // uvs
  35962. var u;
  35963. var v;
  35964. if (customUV) {
  35965. for (p = 0; p < customUV.length; p++) {
  35966. uvs.push(customUV[p].x, customUV[p].y);
  35967. }
  35968. }
  35969. else {
  35970. for (p = 0; p < pathArray.length; p++) {
  35971. for (i = 0; i < minlg + closePathCorr; i++) {
  35972. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  35973. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  35974. if (invertUV) {
  35975. uvs.push(v, u);
  35976. }
  35977. else {
  35978. uvs.push(u, v);
  35979. }
  35980. }
  35981. }
  35982. }
  35983. // indices
  35984. p = 0; // path index
  35985. var pi = 0; // positions array index
  35986. var l1 = lg[p] - 1; // path1 length
  35987. var l2 = lg[p + 1] - 1; // path2 length
  35988. var min = (l1 < l2) ? l1 : l2; // current path stop index
  35989. var shft = idx[1] - idx[0]; // shift
  35990. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  35991. while (pi <= min && p < path1nb) {
  35992. // 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
  35993. indices.push(pi, pi + shft, pi + 1);
  35994. indices.push(pi + shft + 1, pi + 1, pi + shft);
  35995. pi += 1;
  35996. if (pi === min) {
  35997. p++;
  35998. if (p === lg.length - 1) {
  35999. shft = idx[0] - idx[p];
  36000. l1 = lg[p] - 1;
  36001. l2 = lg[0] - 1;
  36002. }
  36003. else {
  36004. shft = idx[p + 1] - idx[p];
  36005. l1 = lg[p] - 1;
  36006. l2 = lg[p + 1] - 1;
  36007. }
  36008. pi = idx[p];
  36009. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36010. }
  36011. }
  36012. // normals
  36013. VertexData.ComputeNormals(positions, indices, normals);
  36014. if (closePath) {
  36015. var indexFirst = 0;
  36016. var indexLast = 0;
  36017. for (p = 0; p < pathArray.length; p++) {
  36018. indexFirst = idx[p] * 3;
  36019. if (p + 1 < pathArray.length) {
  36020. indexLast = (idx[p + 1] - 1) * 3;
  36021. }
  36022. else {
  36023. indexLast = normals.length - 3;
  36024. }
  36025. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36026. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36027. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36028. normals[indexLast] = normals[indexFirst];
  36029. normals[indexLast + 1] = normals[indexFirst + 1];
  36030. normals[indexLast + 2] = normals[indexFirst + 2];
  36031. }
  36032. }
  36033. // sides
  36034. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36035. // Colors
  36036. var colors = null;
  36037. if (customColors) {
  36038. colors = new Float32Array(customColors.length * 4);
  36039. for (var c = 0; c < customColors.length; c++) {
  36040. colors[c * 4] = customColors[c].r;
  36041. colors[c * 4 + 1] = customColors[c].g;
  36042. colors[c * 4 + 2] = customColors[c].b;
  36043. colors[c * 4 + 3] = customColors[c].a;
  36044. }
  36045. }
  36046. // Result
  36047. var vertexData = new VertexData();
  36048. var positions32 = new Float32Array(positions);
  36049. var normals32 = new Float32Array(normals);
  36050. var uvs32 = new Float32Array(uvs);
  36051. vertexData.indices = indices;
  36052. vertexData.positions = positions32;
  36053. vertexData.normals = normals32;
  36054. vertexData.uvs = uvs32;
  36055. if (colors) {
  36056. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36057. }
  36058. if (closePath) {
  36059. vertexData._idx = idx;
  36060. }
  36061. return vertexData;
  36062. };
  36063. /**
  36064. * Creates the VertexData of the Box.
  36065. */
  36066. VertexData.CreateBox = function (options) {
  36067. var normalsSource = [
  36068. new BABYLON.Vector3(0, 0, 1),
  36069. new BABYLON.Vector3(0, 0, -1),
  36070. new BABYLON.Vector3(1, 0, 0),
  36071. new BABYLON.Vector3(-1, 0, 0),
  36072. new BABYLON.Vector3(0, 1, 0),
  36073. new BABYLON.Vector3(0, -1, 0)
  36074. ];
  36075. var indices = [];
  36076. var positions = [];
  36077. var normals = [];
  36078. var uvs = [];
  36079. var width = options.width || options.size || 1;
  36080. var height = options.height || options.size || 1;
  36081. var depth = options.depth || options.size || 1;
  36082. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36083. var faceUV = options.faceUV || new Array(6);
  36084. var faceColors = options.faceColors;
  36085. var colors = [];
  36086. // default face colors and UV if undefined
  36087. for (var f = 0; f < 6; f++) {
  36088. if (faceUV[f] === undefined) {
  36089. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36090. }
  36091. if (faceColors && faceColors[f] === undefined) {
  36092. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36093. }
  36094. }
  36095. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36096. // Create each face in turn.
  36097. for (var index = 0; index < normalsSource.length; index++) {
  36098. var normal = normalsSource[index];
  36099. // Get two vectors perpendicular to the face normal and to each other.
  36100. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36101. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36102. // Six indices (two triangles) per face.
  36103. var verticesLength = positions.length / 3;
  36104. indices.push(verticesLength);
  36105. indices.push(verticesLength + 1);
  36106. indices.push(verticesLength + 2);
  36107. indices.push(verticesLength);
  36108. indices.push(verticesLength + 2);
  36109. indices.push(verticesLength + 3);
  36110. // Four vertices per face.
  36111. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36112. positions.push(vertex.x, vertex.y, vertex.z);
  36113. normals.push(normal.x, normal.y, normal.z);
  36114. uvs.push(faceUV[index].z, faceUV[index].w);
  36115. if (faceColors) {
  36116. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36117. }
  36118. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36119. positions.push(vertex.x, vertex.y, vertex.z);
  36120. normals.push(normal.x, normal.y, normal.z);
  36121. uvs.push(faceUV[index].x, faceUV[index].w);
  36122. if (faceColors) {
  36123. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36124. }
  36125. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36126. positions.push(vertex.x, vertex.y, vertex.z);
  36127. normals.push(normal.x, normal.y, normal.z);
  36128. uvs.push(faceUV[index].x, faceUV[index].y);
  36129. if (faceColors) {
  36130. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36131. }
  36132. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36133. positions.push(vertex.x, vertex.y, vertex.z);
  36134. normals.push(normal.x, normal.y, normal.z);
  36135. uvs.push(faceUV[index].z, faceUV[index].y);
  36136. if (faceColors) {
  36137. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36138. }
  36139. }
  36140. // sides
  36141. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36142. // Result
  36143. var vertexData = new VertexData();
  36144. vertexData.indices = indices;
  36145. vertexData.positions = positions;
  36146. vertexData.normals = normals;
  36147. vertexData.uvs = uvs;
  36148. if (faceColors) {
  36149. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36150. vertexData.colors = totalColors;
  36151. }
  36152. return vertexData;
  36153. };
  36154. /**
  36155. * Creates the VertexData of the Sphere.
  36156. */
  36157. VertexData.CreateSphere = function (options) {
  36158. var segments = options.segments || 32;
  36159. var diameterX = options.diameterX || options.diameter || 1;
  36160. var diameterY = options.diameterY || options.diameter || 1;
  36161. var diameterZ = options.diameterZ || options.diameter || 1;
  36162. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36163. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36164. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36165. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36166. var totalZRotationSteps = 2 + segments;
  36167. var totalYRotationSteps = 2 * totalZRotationSteps;
  36168. var indices = [];
  36169. var positions = [];
  36170. var normals = [];
  36171. var uvs = [];
  36172. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36173. var normalizedZ = zRotationStep / totalZRotationSteps;
  36174. var angleZ = normalizedZ * Math.PI * slice;
  36175. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36176. var normalizedY = yRotationStep / totalYRotationSteps;
  36177. var angleY = normalizedY * Math.PI * 2 * arc;
  36178. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36179. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36180. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36181. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36182. var vertex = complete.multiply(radius);
  36183. var normal = complete.divide(radius).normalize();
  36184. positions.push(vertex.x, vertex.y, vertex.z);
  36185. normals.push(normal.x, normal.y, normal.z);
  36186. uvs.push(normalizedY, normalizedZ);
  36187. }
  36188. if (zRotationStep > 0) {
  36189. var verticesCount = positions.length / 3;
  36190. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36191. indices.push((firstIndex));
  36192. indices.push((firstIndex + 1));
  36193. indices.push(firstIndex + totalYRotationSteps + 1);
  36194. indices.push((firstIndex + totalYRotationSteps + 1));
  36195. indices.push((firstIndex + 1));
  36196. indices.push((firstIndex + totalYRotationSteps + 2));
  36197. }
  36198. }
  36199. }
  36200. // Sides
  36201. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36202. // Result
  36203. var vertexData = new VertexData();
  36204. vertexData.indices = indices;
  36205. vertexData.positions = positions;
  36206. vertexData.normals = normals;
  36207. vertexData.uvs = uvs;
  36208. return vertexData;
  36209. };
  36210. /**
  36211. * Creates the VertexData of the Cylinder or Cone.
  36212. */
  36213. VertexData.CreateCylinder = function (options) {
  36214. var height = options.height || 2;
  36215. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36216. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36217. var tessellation = options.tessellation || 24;
  36218. var subdivisions = options.subdivisions || 1;
  36219. var hasRings = options.hasRings ? true : false;
  36220. var enclose = options.enclose ? true : false;
  36221. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36222. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36223. var faceUV = options.faceUV || new Array(3);
  36224. var faceColors = options.faceColors;
  36225. // default face colors and UV if undefined
  36226. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36227. var ringNb = (hasRings) ? subdivisions : 1;
  36228. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36229. var f;
  36230. for (f = 0; f < surfaceNb; f++) {
  36231. if (faceColors && faceColors[f] === undefined) {
  36232. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36233. }
  36234. }
  36235. for (f = 0; f < surfaceNb; f++) {
  36236. if (faceUV && faceUV[f] === undefined) {
  36237. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36238. }
  36239. }
  36240. var indices = new Array();
  36241. var positions = new Array();
  36242. var normals = new Array();
  36243. var uvs = new Array();
  36244. var colors = new Array();
  36245. var angle_step = Math.PI * 2 * arc / tessellation;
  36246. var angle;
  36247. var h;
  36248. var radius;
  36249. var tan = (diameterBottom - diameterTop) / 2 / height;
  36250. var ringVertex = BABYLON.Vector3.Zero();
  36251. var ringNormal = BABYLON.Vector3.Zero();
  36252. var ringFirstVertex = BABYLON.Vector3.Zero();
  36253. var ringFirstNormal = BABYLON.Vector3.Zero();
  36254. var quadNormal = BABYLON.Vector3.Zero();
  36255. var Y = BABYLON.Axis.Y;
  36256. // positions, normals, uvs
  36257. var i;
  36258. var j;
  36259. var r;
  36260. var ringIdx = 1;
  36261. var s = 1; // surface index
  36262. var cs = 0;
  36263. var v = 0;
  36264. for (i = 0; i <= subdivisions; i++) {
  36265. h = i / subdivisions;
  36266. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36267. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36268. for (r = 0; r < ringIdx; r++) {
  36269. if (hasRings) {
  36270. s += r;
  36271. }
  36272. if (enclose) {
  36273. s += 2 * r;
  36274. }
  36275. for (j = 0; j <= tessellation; j++) {
  36276. angle = j * angle_step;
  36277. // position
  36278. ringVertex.x = Math.cos(-angle) * radius;
  36279. ringVertex.y = -height / 2 + h * height;
  36280. ringVertex.z = Math.sin(-angle) * radius;
  36281. // normal
  36282. if (diameterTop === 0 && i === subdivisions) {
  36283. // if no top cap, reuse former normals
  36284. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36285. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36286. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36287. }
  36288. else {
  36289. ringNormal.x = ringVertex.x;
  36290. ringNormal.z = ringVertex.z;
  36291. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36292. ringNormal.normalize();
  36293. }
  36294. // keep first ring vertex values for enclose
  36295. if (j === 0) {
  36296. ringFirstVertex.copyFrom(ringVertex);
  36297. ringFirstNormal.copyFrom(ringNormal);
  36298. }
  36299. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36300. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36301. if (hasRings) {
  36302. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36303. }
  36304. else {
  36305. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36306. }
  36307. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36308. if (faceColors) {
  36309. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36310. }
  36311. }
  36312. // if enclose, add four vertices and their dedicated normals
  36313. if (arc !== 1 && enclose) {
  36314. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36315. positions.push(0, ringVertex.y, 0);
  36316. positions.push(0, ringVertex.y, 0);
  36317. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36318. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36319. quadNormal.normalize();
  36320. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36321. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36322. quadNormal.normalize();
  36323. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36324. if (hasRings) {
  36325. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36326. }
  36327. else {
  36328. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36329. }
  36330. uvs.push(faceUV[s + 1].x, v);
  36331. uvs.push(faceUV[s + 1].z, v);
  36332. if (hasRings) {
  36333. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36334. }
  36335. else {
  36336. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36337. }
  36338. uvs.push(faceUV[s + 2].x, v);
  36339. uvs.push(faceUV[s + 2].z, v);
  36340. if (faceColors) {
  36341. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36342. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36343. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36344. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36345. }
  36346. }
  36347. if (cs !== s) {
  36348. cs = s;
  36349. }
  36350. }
  36351. }
  36352. // indices
  36353. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36354. var s;
  36355. i = 0;
  36356. for (s = 0; s < subdivisions; s++) {
  36357. var i0 = 0;
  36358. var i1 = 0;
  36359. var i2 = 0;
  36360. var i3 = 0;
  36361. for (j = 0; j < tessellation; j++) {
  36362. i0 = i * (e + 1) + j;
  36363. i1 = (i + 1) * (e + 1) + j;
  36364. i2 = i * (e + 1) + (j + 1);
  36365. i3 = (i + 1) * (e + 1) + (j + 1);
  36366. indices.push(i0, i1, i2);
  36367. indices.push(i3, i2, i1);
  36368. }
  36369. if (arc !== 1 && enclose) {
  36370. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36371. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36372. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36373. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36374. }
  36375. i = (hasRings) ? (i + 2) : (i + 1);
  36376. }
  36377. // Caps
  36378. var createCylinderCap = function (isTop) {
  36379. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36380. if (radius === 0) {
  36381. return;
  36382. }
  36383. // Cap positions, normals & uvs
  36384. var angle;
  36385. var circleVector;
  36386. var i;
  36387. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36388. var c = null;
  36389. if (faceColors) {
  36390. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36391. }
  36392. // cap center
  36393. var vbase = positions.length / 3;
  36394. var offset = isTop ? height / 2 : -height / 2;
  36395. var center = new BABYLON.Vector3(0, offset, 0);
  36396. positions.push(center.x, center.y, center.z);
  36397. normals.push(0, isTop ? 1 : -1, 0);
  36398. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36399. if (c) {
  36400. colors.push(c.r, c.g, c.b, c.a);
  36401. }
  36402. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36403. for (i = 0; i <= tessellation; i++) {
  36404. angle = Math.PI * 2 * i * arc / tessellation;
  36405. var cos = Math.cos(-angle);
  36406. var sin = Math.sin(-angle);
  36407. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36408. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36409. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36410. normals.push(0, isTop ? 1 : -1, 0);
  36411. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36412. if (c) {
  36413. colors.push(c.r, c.g, c.b, c.a);
  36414. }
  36415. }
  36416. // Cap indices
  36417. for (i = 0; i < tessellation; i++) {
  36418. if (!isTop) {
  36419. indices.push(vbase);
  36420. indices.push(vbase + (i + 1));
  36421. indices.push(vbase + (i + 2));
  36422. }
  36423. else {
  36424. indices.push(vbase);
  36425. indices.push(vbase + (i + 2));
  36426. indices.push(vbase + (i + 1));
  36427. }
  36428. }
  36429. };
  36430. // add caps to geometry
  36431. createCylinderCap(false);
  36432. createCylinderCap(true);
  36433. // Sides
  36434. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36435. var vertexData = new VertexData();
  36436. vertexData.indices = indices;
  36437. vertexData.positions = positions;
  36438. vertexData.normals = normals;
  36439. vertexData.uvs = uvs;
  36440. if (faceColors) {
  36441. vertexData.colors = colors;
  36442. }
  36443. return vertexData;
  36444. };
  36445. /**
  36446. * Creates the VertexData of the Torus.
  36447. */
  36448. VertexData.CreateTorus = function (options) {
  36449. var indices = [];
  36450. var positions = [];
  36451. var normals = [];
  36452. var uvs = [];
  36453. var diameter = options.diameter || 1;
  36454. var thickness = options.thickness || 0.5;
  36455. var tessellation = options.tessellation || 16;
  36456. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36457. var stride = tessellation + 1;
  36458. for (var i = 0; i <= tessellation; i++) {
  36459. var u = i / tessellation;
  36460. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36461. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36462. for (var j = 0; j <= tessellation; j++) {
  36463. var v = 1 - j / tessellation;
  36464. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36465. var dx = Math.cos(innerAngle);
  36466. var dy = Math.sin(innerAngle);
  36467. // Create a vertex.
  36468. var normal = new BABYLON.Vector3(dx, dy, 0);
  36469. var position = normal.scale(thickness / 2);
  36470. var textureCoordinate = new BABYLON.Vector2(u, v);
  36471. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36472. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36473. positions.push(position.x, position.y, position.z);
  36474. normals.push(normal.x, normal.y, normal.z);
  36475. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36476. // And create indices for two triangles.
  36477. var nextI = (i + 1) % stride;
  36478. var nextJ = (j + 1) % stride;
  36479. indices.push(i * stride + j);
  36480. indices.push(i * stride + nextJ);
  36481. indices.push(nextI * stride + j);
  36482. indices.push(i * stride + nextJ);
  36483. indices.push(nextI * stride + nextJ);
  36484. indices.push(nextI * stride + j);
  36485. }
  36486. }
  36487. // Sides
  36488. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36489. // Result
  36490. var vertexData = new VertexData();
  36491. vertexData.indices = indices;
  36492. vertexData.positions = positions;
  36493. vertexData.normals = normals;
  36494. vertexData.uvs = uvs;
  36495. return vertexData;
  36496. };
  36497. /**
  36498. * Creates the VertexData of the LineSystem.
  36499. */
  36500. VertexData.CreateLineSystem = function (options) {
  36501. var indices = [];
  36502. var positions = [];
  36503. var lines = options.lines;
  36504. var colors = options.colors;
  36505. var vertexColors = [];
  36506. var idx = 0;
  36507. for (var l = 0; l < lines.length; l++) {
  36508. var points = lines[l];
  36509. for (var index = 0; index < points.length; index++) {
  36510. positions.push(points[index].x, points[index].y, points[index].z);
  36511. if (colors) {
  36512. var color = colors[l];
  36513. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36514. }
  36515. if (index > 0) {
  36516. indices.push(idx - 1);
  36517. indices.push(idx);
  36518. }
  36519. idx++;
  36520. }
  36521. }
  36522. var vertexData = new VertexData();
  36523. vertexData.indices = indices;
  36524. vertexData.positions = positions;
  36525. if (colors) {
  36526. vertexData.colors = vertexColors;
  36527. }
  36528. return vertexData;
  36529. };
  36530. /**
  36531. * Create the VertexData of the DashedLines.
  36532. */
  36533. VertexData.CreateDashedLines = function (options) {
  36534. var dashSize = options.dashSize || 3;
  36535. var gapSize = options.gapSize || 1;
  36536. var dashNb = options.dashNb || 200;
  36537. var points = options.points;
  36538. var positions = new Array();
  36539. var indices = new Array();
  36540. var curvect = BABYLON.Vector3.Zero();
  36541. var lg = 0;
  36542. var nb = 0;
  36543. var shft = 0;
  36544. var dashshft = 0;
  36545. var curshft = 0;
  36546. var idx = 0;
  36547. var i = 0;
  36548. for (i = 0; i < points.length - 1; i++) {
  36549. points[i + 1].subtractToRef(points[i], curvect);
  36550. lg += curvect.length();
  36551. }
  36552. shft = lg / dashNb;
  36553. dashshft = dashSize * shft / (dashSize + gapSize);
  36554. for (i = 0; i < points.length - 1; i++) {
  36555. points[i + 1].subtractToRef(points[i], curvect);
  36556. nb = Math.floor(curvect.length() / shft);
  36557. curvect.normalize();
  36558. for (var j = 0; j < nb; j++) {
  36559. curshft = shft * j;
  36560. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36561. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36562. indices.push(idx, idx + 1);
  36563. idx += 2;
  36564. }
  36565. }
  36566. // Result
  36567. var vertexData = new VertexData();
  36568. vertexData.positions = positions;
  36569. vertexData.indices = indices;
  36570. return vertexData;
  36571. };
  36572. /**
  36573. * Creates the VertexData of the Ground.
  36574. */
  36575. VertexData.CreateGround = function (options) {
  36576. var indices = [];
  36577. var positions = [];
  36578. var normals = [];
  36579. var uvs = [];
  36580. var row, col;
  36581. var width = options.width || 1;
  36582. var height = options.height || 1;
  36583. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36584. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36585. for (row = 0; row <= subdivisionsY; row++) {
  36586. for (col = 0; col <= subdivisionsX; col++) {
  36587. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36588. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36589. positions.push(position.x, position.y, position.z);
  36590. normals.push(normal.x, normal.y, normal.z);
  36591. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36592. }
  36593. }
  36594. for (row = 0; row < subdivisionsY; row++) {
  36595. for (col = 0; col < subdivisionsX; col++) {
  36596. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36597. indices.push(col + 1 + row * (subdivisionsX + 1));
  36598. indices.push(col + row * (subdivisionsX + 1));
  36599. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36600. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36601. indices.push(col + row * (subdivisionsX + 1));
  36602. }
  36603. }
  36604. // Result
  36605. var vertexData = new VertexData();
  36606. vertexData.indices = indices;
  36607. vertexData.positions = positions;
  36608. vertexData.normals = normals;
  36609. vertexData.uvs = uvs;
  36610. return vertexData;
  36611. };
  36612. /**
  36613. * Creates the VertexData of the TiledGround.
  36614. */
  36615. VertexData.CreateTiledGround = function (options) {
  36616. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  36617. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  36618. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  36619. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  36620. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36621. var precision = options.precision || { w: 1, h: 1 };
  36622. var indices = new Array();
  36623. var positions = new Array();
  36624. var normals = new Array();
  36625. var uvs = new Array();
  36626. var row, col, tileRow, tileCol;
  36627. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36628. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36629. precision.w = (precision.w < 1) ? 1 : precision.w;
  36630. precision.h = (precision.h < 1) ? 1 : precision.h;
  36631. var tileSize = {
  36632. 'w': (xmax - xmin) / subdivisions.w,
  36633. 'h': (zmax - zmin) / subdivisions.h
  36634. };
  36635. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36636. // Indices
  36637. var base = positions.length / 3;
  36638. var rowLength = precision.w + 1;
  36639. for (row = 0; row < precision.h; row++) {
  36640. for (col = 0; col < precision.w; col++) {
  36641. var square = [
  36642. base + col + row * rowLength,
  36643. base + (col + 1) + row * rowLength,
  36644. base + (col + 1) + (row + 1) * rowLength,
  36645. base + col + (row + 1) * rowLength
  36646. ];
  36647. indices.push(square[1]);
  36648. indices.push(square[2]);
  36649. indices.push(square[3]);
  36650. indices.push(square[0]);
  36651. indices.push(square[1]);
  36652. indices.push(square[3]);
  36653. }
  36654. }
  36655. // Position, normals and uvs
  36656. var position = BABYLON.Vector3.Zero();
  36657. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36658. for (row = 0; row <= precision.h; row++) {
  36659. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  36660. for (col = 0; col <= precision.w; col++) {
  36661. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  36662. position.y = 0;
  36663. positions.push(position.x, position.y, position.z);
  36664. normals.push(normal.x, normal.y, normal.z);
  36665. uvs.push(col / precision.w, row / precision.h);
  36666. }
  36667. }
  36668. }
  36669. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  36670. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  36671. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  36672. }
  36673. }
  36674. // Result
  36675. var vertexData = new VertexData();
  36676. vertexData.indices = indices;
  36677. vertexData.positions = positions;
  36678. vertexData.normals = normals;
  36679. vertexData.uvs = uvs;
  36680. return vertexData;
  36681. };
  36682. /**
  36683. * Creates the VertexData of the Ground designed from a heightmap.
  36684. */
  36685. VertexData.CreateGroundFromHeightMap = function (options) {
  36686. var indices = [];
  36687. var positions = [];
  36688. var normals = [];
  36689. var uvs = [];
  36690. var row, col;
  36691. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  36692. // Vertices
  36693. for (row = 0; row <= options.subdivisions; row++) {
  36694. for (col = 0; col <= options.subdivisions; col++) {
  36695. 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));
  36696. // Compute height
  36697. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  36698. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  36699. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  36700. var r = options.buffer[pos] / 255.0;
  36701. var g = options.buffer[pos + 1] / 255.0;
  36702. var b = options.buffer[pos + 2] / 255.0;
  36703. var gradient = r * filter.r + g * filter.g + b * filter.b;
  36704. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  36705. // Add vertex
  36706. positions.push(position.x, position.y, position.z);
  36707. normals.push(0, 0, 0);
  36708. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  36709. }
  36710. }
  36711. // Indices
  36712. for (row = 0; row < options.subdivisions; row++) {
  36713. for (col = 0; col < options.subdivisions; col++) {
  36714. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36715. indices.push(col + 1 + row * (options.subdivisions + 1));
  36716. indices.push(col + row * (options.subdivisions + 1));
  36717. indices.push(col + (row + 1) * (options.subdivisions + 1));
  36718. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36719. indices.push(col + row * (options.subdivisions + 1));
  36720. }
  36721. }
  36722. // Normals
  36723. VertexData.ComputeNormals(positions, indices, normals);
  36724. // Result
  36725. var vertexData = new VertexData();
  36726. vertexData.indices = indices;
  36727. vertexData.positions = positions;
  36728. vertexData.normals = normals;
  36729. vertexData.uvs = uvs;
  36730. return vertexData;
  36731. };
  36732. /**
  36733. * Creates the VertexData of the Plane.
  36734. */
  36735. VertexData.CreatePlane = function (options) {
  36736. var indices = [];
  36737. var positions = [];
  36738. var normals = [];
  36739. var uvs = [];
  36740. var width = options.width || options.size || 1;
  36741. var height = options.height || options.size || 1;
  36742. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36743. // Vertices
  36744. var halfWidth = width / 2.0;
  36745. var halfHeight = height / 2.0;
  36746. positions.push(-halfWidth, -halfHeight, 0);
  36747. normals.push(0, 0, -1.0);
  36748. uvs.push(0.0, 0.0);
  36749. positions.push(halfWidth, -halfHeight, 0);
  36750. normals.push(0, 0, -1.0);
  36751. uvs.push(1.0, 0.0);
  36752. positions.push(halfWidth, halfHeight, 0);
  36753. normals.push(0, 0, -1.0);
  36754. uvs.push(1.0, 1.0);
  36755. positions.push(-halfWidth, halfHeight, 0);
  36756. normals.push(0, 0, -1.0);
  36757. uvs.push(0.0, 1.0);
  36758. // Indices
  36759. indices.push(0);
  36760. indices.push(1);
  36761. indices.push(2);
  36762. indices.push(0);
  36763. indices.push(2);
  36764. indices.push(3);
  36765. // Sides
  36766. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36767. // Result
  36768. var vertexData = new VertexData();
  36769. vertexData.indices = indices;
  36770. vertexData.positions = positions;
  36771. vertexData.normals = normals;
  36772. vertexData.uvs = uvs;
  36773. return vertexData;
  36774. };
  36775. /**
  36776. * Creates the VertexData of the Disc or regular Polygon.
  36777. */
  36778. VertexData.CreateDisc = function (options) {
  36779. var positions = new Array();
  36780. var indices = new Array();
  36781. var normals = new Array();
  36782. var uvs = new Array();
  36783. var radius = options.radius || 0.5;
  36784. var tessellation = options.tessellation || 64;
  36785. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36786. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36787. // positions and uvs
  36788. positions.push(0, 0, 0); // disc center first
  36789. uvs.push(0.5, 0.5);
  36790. var theta = Math.PI * 2 * arc;
  36791. var step = theta / tessellation;
  36792. for (var a = 0; a < theta; a += step) {
  36793. var x = Math.cos(a);
  36794. var y = Math.sin(a);
  36795. var u = (x + 1) / 2;
  36796. var v = (1 - y) / 2;
  36797. positions.push(radius * x, radius * y, 0);
  36798. uvs.push(u, v);
  36799. }
  36800. if (arc === 1) {
  36801. positions.push(positions[3], positions[4], positions[5]); // close the circle
  36802. uvs.push(uvs[2], uvs[3]);
  36803. }
  36804. //indices
  36805. var vertexNb = positions.length / 3;
  36806. for (var i = 1; i < vertexNb - 1; i++) {
  36807. indices.push(i + 1, 0, i);
  36808. }
  36809. // result
  36810. VertexData.ComputeNormals(positions, indices, normals);
  36811. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36812. var vertexData = new VertexData();
  36813. vertexData.indices = indices;
  36814. vertexData.positions = positions;
  36815. vertexData.normals = normals;
  36816. vertexData.uvs = uvs;
  36817. return vertexData;
  36818. };
  36819. /**
  36820. * Re-creates the VertexData of the Polygon for sideOrientation.
  36821. */
  36822. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  36823. var faceUV = fUV || new Array(3);
  36824. var faceColors = fColors;
  36825. var colors = [];
  36826. // default face colors and UV if undefined
  36827. for (var f = 0; f < 3; f++) {
  36828. if (faceUV[f] === undefined) {
  36829. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36830. }
  36831. if (faceColors && faceColors[f] === undefined) {
  36832. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36833. }
  36834. }
  36835. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36836. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36837. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36838. var indices = polygon.getIndices();
  36839. // set face colours and textures
  36840. var idx = 0;
  36841. var face = 0;
  36842. for (var index = 0; index < normals.length; index += 3) {
  36843. //Edge Face no. 1
  36844. if (Math.abs(normals[index + 1]) < 0.001) {
  36845. face = 1;
  36846. }
  36847. //Top Face no. 0
  36848. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  36849. face = 0;
  36850. }
  36851. //Bottom Face no. 2
  36852. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  36853. face = 2;
  36854. }
  36855. idx = index / 3;
  36856. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  36857. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  36858. if (faceColors) {
  36859. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  36860. }
  36861. }
  36862. // sides
  36863. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  36864. // Result
  36865. var vertexData = new VertexData();
  36866. vertexData.indices = indices;
  36867. vertexData.positions = positions;
  36868. vertexData.normals = normals;
  36869. vertexData.uvs = uvs;
  36870. if (faceColors) {
  36871. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36872. vertexData.colors = totalColors;
  36873. }
  36874. return vertexData;
  36875. };
  36876. /**
  36877. * Creates the VertexData of the IcoSphere.
  36878. */
  36879. VertexData.CreateIcoSphere = function (options) {
  36880. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36881. var radius = options.radius || 1;
  36882. var flat = (options.flat === undefined) ? true : options.flat;
  36883. var subdivisions = options.subdivisions || 4;
  36884. var radiusX = options.radiusX || radius;
  36885. var radiusY = options.radiusY || radius;
  36886. var radiusZ = options.radiusZ || radius;
  36887. var t = (1 + Math.sqrt(5)) / 2;
  36888. // 12 vertex x,y,z
  36889. var ico_vertices = [
  36890. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  36891. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  36892. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  36893. ];
  36894. // index of 3 vertex makes a face of icopshere
  36895. var ico_indices = [
  36896. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  36897. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  36898. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  36899. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  36900. ];
  36901. // vertex for uv have aliased position, not for UV
  36902. var vertices_unalias_id = [
  36903. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  36904. // vertex alias
  36905. 0,
  36906. 2,
  36907. 3,
  36908. 3,
  36909. 3,
  36910. 4,
  36911. 7,
  36912. 8,
  36913. 9,
  36914. 9,
  36915. 10,
  36916. 11 // 23: B + 12
  36917. ];
  36918. // uv as integer step (not pixels !)
  36919. var ico_vertexuv = [
  36920. 5, 1, 3, 1, 6, 4, 0, 0,
  36921. 5, 3, 4, 2, 2, 2, 4, 0,
  36922. 2, 0, 1, 1, 6, 0, 6, 2,
  36923. // vertex alias (for same vertex on different faces)
  36924. 0, 4,
  36925. 3, 3,
  36926. 4, 4,
  36927. 3, 1,
  36928. 4, 2,
  36929. 4, 4,
  36930. 0, 2,
  36931. 1, 1,
  36932. 2, 2,
  36933. 3, 3,
  36934. 1, 3,
  36935. 2, 4 // 23: B + 12
  36936. ];
  36937. // Vertices[0, 1, ...9, A, B] : position on UV plane
  36938. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  36939. // First island of uv mapping
  36940. // v = 4h 3+ 2
  36941. // v = 3h 9+ 4
  36942. // v = 2h 9+ 5 B
  36943. // v = 1h 9 1 0
  36944. // v = 0h 3 8 7 A
  36945. // u = 0 1 2 3 4 5 6 *a
  36946. // Second island of uv mapping
  36947. // v = 4h 0+ B+ 4+
  36948. // v = 3h A+ 2+
  36949. // v = 2h 7+ 6 3+
  36950. // v = 1h 8+ 3+
  36951. // v = 0h
  36952. // u = 0 1 2 3 4 5 6 *a
  36953. // Face layout on texture UV mapping
  36954. // ============
  36955. // \ 4 /\ 16 / ======
  36956. // \ / \ / /\ 11 /
  36957. // \/ 7 \/ / \ /
  36958. // ======= / 10 \/
  36959. // /\ 17 /\ =======
  36960. // / \ / \ \ 15 /\
  36961. // / 8 \/ 12 \ \ / \
  36962. // ============ \/ 6 \
  36963. // \ 18 /\ ============
  36964. // \ / \ \ 5 /\ 0 /
  36965. // \/ 13 \ \ / \ /
  36966. // ======= \/ 1 \/
  36967. // =============
  36968. // /\ 19 /\ 2 /\
  36969. // / \ / \ / \
  36970. // / 14 \/ 9 \/ 3 \
  36971. // ===================
  36972. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  36973. var ustep = 138 / 1024;
  36974. var vstep = 239 / 1024;
  36975. var uoffset = 60 / 1024;
  36976. var voffset = 26 / 1024;
  36977. // Second island should have margin, not to touch the first island
  36978. // avoid any borderline artefact in pixel rounding
  36979. var island_u_offset = -40 / 1024;
  36980. var island_v_offset = +20 / 1024;
  36981. // face is either island 0 or 1 :
  36982. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  36983. var island = [
  36984. 0, 0, 0, 0, 1,
  36985. 0, 0, 1, 1, 0,
  36986. 0, 0, 1, 1, 0,
  36987. 0, 1, 1, 1, 0 // 15 - 19
  36988. ];
  36989. var indices = new Array();
  36990. var positions = new Array();
  36991. var normals = new Array();
  36992. var uvs = new Array();
  36993. var current_indice = 0;
  36994. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  36995. var face_vertex_pos = new Array(3);
  36996. var face_vertex_uv = new Array(3);
  36997. var v012;
  36998. for (v012 = 0; v012 < 3; v012++) {
  36999. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37000. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37001. }
  37002. // create all with normals
  37003. for (var face = 0; face < 20; face++) {
  37004. // 3 vertex per face
  37005. for (v012 = 0; v012 < 3; v012++) {
  37006. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37007. var v_id = ico_indices[3 * face + v012];
  37008. // vertex have 3D position (x,y,z)
  37009. 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]);
  37010. // Normalize to get normal, then scale to radius
  37011. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37012. // uv Coordinates from vertex ID
  37013. 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);
  37014. }
  37015. // Subdivide the face (interpolate pos, norm, uv)
  37016. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37017. // - norm is linear interpolation of vertex corner normal
  37018. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37019. // - uv is linear interpolation
  37020. //
  37021. // Topology is as below for sub-divide by 2
  37022. // vertex shown as v0,v1,v2
  37023. // interp index is i1 to progress in range [v0,v1[
  37024. // interp index is i2 to progress in range [v0,v2[
  37025. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37026. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37027. //
  37028. //
  37029. // i2 v2
  37030. // ^ ^
  37031. // / / \
  37032. // / / \
  37033. // / / \
  37034. // / / (0,1) \
  37035. // / #---------\
  37036. // / / \ (0,0)'/ \
  37037. // / / \ / \
  37038. // / / \ / \
  37039. // / / (0,0) \ / (1,0) \
  37040. // / #---------#---------\
  37041. // v0 v1
  37042. //
  37043. // --------------------> i1
  37044. //
  37045. // interp of (i1,i2):
  37046. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37047. // along i1 : lerp(x0,x1, i1/(S-i2))
  37048. //
  37049. // centroid of triangle is needed to get help normal computation
  37050. // (c1,c2) are used for centroid location
  37051. var interp_vertex = function (i1, i2, c1, c2) {
  37052. // vertex is interpolated from
  37053. // - face_vertex_pos[0..2]
  37054. // - face_vertex_uv[0..2]
  37055. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37056. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37057. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37058. pos_interp.normalize();
  37059. var vertex_normal;
  37060. if (flat) {
  37061. // in flat mode, recalculate normal as face centroid normal
  37062. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37063. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37064. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37065. }
  37066. else {
  37067. // in smooth mode, recalculate normal from each single vertex position
  37068. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37069. }
  37070. // Vertex normal need correction due to X,Y,Z radius scaling
  37071. vertex_normal.x /= radiusX;
  37072. vertex_normal.y /= radiusY;
  37073. vertex_normal.z /= radiusZ;
  37074. vertex_normal.normalize();
  37075. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37076. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37077. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37078. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37079. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37080. uvs.push(uv_interp.x, uv_interp.y);
  37081. // push each vertex has member of a face
  37082. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37083. indices.push(current_indice);
  37084. current_indice++;
  37085. };
  37086. for (var i2 = 0; i2 < subdivisions; i2++) {
  37087. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37088. // face : (i1,i2) for /\ :
  37089. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37090. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37091. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37092. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37093. if (i1 + i2 + 1 < subdivisions) {
  37094. // face : (i1,i2)' for \/ :
  37095. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37096. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37097. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37098. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37099. }
  37100. }
  37101. }
  37102. }
  37103. // Sides
  37104. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37105. // Result
  37106. var vertexData = new VertexData();
  37107. vertexData.indices = indices;
  37108. vertexData.positions = positions;
  37109. vertexData.normals = normals;
  37110. vertexData.uvs = uvs;
  37111. return vertexData;
  37112. };
  37113. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37114. /**
  37115. * Creates the VertexData of the Polyhedron.
  37116. */
  37117. VertexData.CreatePolyhedron = function (options) {
  37118. // provided polyhedron types :
  37119. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37120. // 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)
  37121. var polyhedra = [];
  37122. 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]] };
  37123. 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]] };
  37124. polyhedra[2] = {
  37125. 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]],
  37126. 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]]
  37127. };
  37128. polyhedra[3] = {
  37129. 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]],
  37130. 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]]
  37131. };
  37132. polyhedra[4] = {
  37133. 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]],
  37134. 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]]
  37135. };
  37136. 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]] };
  37137. 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]] };
  37138. 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]] };
  37139. 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]] };
  37140. 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]] };
  37141. 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]] };
  37142. 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]] };
  37143. 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]] };
  37144. 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]] };
  37145. polyhedra[14] = {
  37146. 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]],
  37147. 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]]
  37148. };
  37149. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37150. var size = options.size;
  37151. var sizeX = options.sizeX || size || 1;
  37152. var sizeY = options.sizeY || size || 1;
  37153. var sizeZ = options.sizeZ || size || 1;
  37154. var data = options.custom || polyhedra[type];
  37155. var nbfaces = data.face.length;
  37156. var faceUV = options.faceUV || new Array(nbfaces);
  37157. var faceColors = options.faceColors;
  37158. var flat = (options.flat === undefined) ? true : options.flat;
  37159. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37160. var positions = new Array();
  37161. var indices = new Array();
  37162. var normals = new Array();
  37163. var uvs = new Array();
  37164. var colors = new Array();
  37165. var index = 0;
  37166. var faceIdx = 0; // face cursor in the array "indexes"
  37167. var indexes = new Array();
  37168. var i = 0;
  37169. var f = 0;
  37170. var u, v, ang, x, y, tmp;
  37171. // default face colors and UV if undefined
  37172. if (flat) {
  37173. for (f = 0; f < nbfaces; f++) {
  37174. if (faceColors && faceColors[f] === undefined) {
  37175. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37176. }
  37177. if (faceUV && faceUV[f] === undefined) {
  37178. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37179. }
  37180. }
  37181. }
  37182. if (!flat) {
  37183. for (i = 0; i < data.vertex.length; i++) {
  37184. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37185. uvs.push(0, 0);
  37186. }
  37187. for (f = 0; f < nbfaces; f++) {
  37188. for (i = 0; i < data.face[f].length - 2; i++) {
  37189. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37190. }
  37191. }
  37192. }
  37193. else {
  37194. for (f = 0; f < nbfaces; f++) {
  37195. var fl = data.face[f].length; // number of vertices of the current face
  37196. ang = 2 * Math.PI / fl;
  37197. x = 0.5 * Math.tan(ang / 2);
  37198. y = 0.5;
  37199. // positions, uvs, colors
  37200. for (i = 0; i < fl; i++) {
  37201. // positions
  37202. 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);
  37203. indexes.push(index);
  37204. index++;
  37205. // uvs
  37206. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37207. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37208. uvs.push(u, v);
  37209. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37210. y = x * Math.sin(ang) + y * Math.cos(ang);
  37211. x = tmp;
  37212. // colors
  37213. if (faceColors) {
  37214. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37215. }
  37216. }
  37217. // indices from indexes
  37218. for (i = 0; i < fl - 2; i++) {
  37219. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37220. }
  37221. faceIdx += fl;
  37222. }
  37223. }
  37224. VertexData.ComputeNormals(positions, indices, normals);
  37225. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37226. var vertexData = new VertexData();
  37227. vertexData.positions = positions;
  37228. vertexData.indices = indices;
  37229. vertexData.normals = normals;
  37230. vertexData.uvs = uvs;
  37231. if (faceColors && flat) {
  37232. vertexData.colors = colors;
  37233. }
  37234. return vertexData;
  37235. };
  37236. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37237. /**
  37238. * Creates the VertexData of the Torus Knot.
  37239. */
  37240. VertexData.CreateTorusKnot = function (options) {
  37241. var indices = new Array();
  37242. var positions = new Array();
  37243. var normals = new Array();
  37244. var uvs = new Array();
  37245. var radius = options.radius || 2;
  37246. var tube = options.tube || 0.5;
  37247. var radialSegments = options.radialSegments || 32;
  37248. var tubularSegments = options.tubularSegments || 32;
  37249. var p = options.p || 2;
  37250. var q = options.q || 3;
  37251. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37252. // Helper
  37253. var getPos = function (angle) {
  37254. var cu = Math.cos(angle);
  37255. var su = Math.sin(angle);
  37256. var quOverP = q / p * angle;
  37257. var cs = Math.cos(quOverP);
  37258. var tx = radius * (2 + cs) * 0.5 * cu;
  37259. var ty = radius * (2 + cs) * su * 0.5;
  37260. var tz = radius * Math.sin(quOverP) * 0.5;
  37261. return new BABYLON.Vector3(tx, ty, tz);
  37262. };
  37263. // Vertices
  37264. var i;
  37265. var j;
  37266. for (i = 0; i <= radialSegments; i++) {
  37267. var modI = i % radialSegments;
  37268. var u = modI / radialSegments * 2 * p * Math.PI;
  37269. var p1 = getPos(u);
  37270. var p2 = getPos(u + 0.01);
  37271. var tang = p2.subtract(p1);
  37272. var n = p2.add(p1);
  37273. var bitan = BABYLON.Vector3.Cross(tang, n);
  37274. n = BABYLON.Vector3.Cross(bitan, tang);
  37275. bitan.normalize();
  37276. n.normalize();
  37277. for (j = 0; j < tubularSegments; j++) {
  37278. var modJ = j % tubularSegments;
  37279. var v = modJ / tubularSegments * 2 * Math.PI;
  37280. var cx = -tube * Math.cos(v);
  37281. var cy = tube * Math.sin(v);
  37282. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37283. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37284. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37285. uvs.push(i / radialSegments);
  37286. uvs.push(j / tubularSegments);
  37287. }
  37288. }
  37289. for (i = 0; i < radialSegments; i++) {
  37290. for (j = 0; j < tubularSegments; j++) {
  37291. var jNext = (j + 1) % tubularSegments;
  37292. var a = i * tubularSegments + j;
  37293. var b = (i + 1) * tubularSegments + j;
  37294. var c = (i + 1) * tubularSegments + jNext;
  37295. var d = i * tubularSegments + jNext;
  37296. indices.push(d);
  37297. indices.push(b);
  37298. indices.push(a);
  37299. indices.push(d);
  37300. indices.push(c);
  37301. indices.push(b);
  37302. }
  37303. }
  37304. // Normals
  37305. VertexData.ComputeNormals(positions, indices, normals);
  37306. // Sides
  37307. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37308. // Result
  37309. var vertexData = new VertexData();
  37310. vertexData.indices = indices;
  37311. vertexData.positions = positions;
  37312. vertexData.normals = normals;
  37313. vertexData.uvs = uvs;
  37314. return vertexData;
  37315. };
  37316. // Tools
  37317. /**
  37318. * @param {any} - positions (number[] or Float32Array)
  37319. * @param {any} - indices (number[] or Uint16Array)
  37320. * @param {any} - normals (number[] or Float32Array)
  37321. * options (optional) :
  37322. * facetPositions : optional array of facet positions (vector3)
  37323. * facetNormals : optional array of facet normals (vector3)
  37324. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37325. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37326. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37327. * bbSize : optional bounding box size data, required for facetPartitioning computation
  37328. * bInfo : optional bounding info, required for facetPartitioning computation
  37329. * useRightHandedSystem: optional boolean to for right handed system computation
  37330. * depthSort : optional boolean to enable the facet depth sort computation
  37331. * distanceTo : optional Vector3 to compute the facet depth from this location
  37332. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37333. */
  37334. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37335. // temporary scalar variables
  37336. var index = 0; // facet index
  37337. var p1p2x = 0.0; // p1p2 vector x coordinate
  37338. var p1p2y = 0.0; // p1p2 vector y coordinate
  37339. var p1p2z = 0.0; // p1p2 vector z coordinate
  37340. var p3p2x = 0.0; // p3p2 vector x coordinate
  37341. var p3p2y = 0.0; // p3p2 vector y coordinate
  37342. var p3p2z = 0.0; // p3p2 vector z coordinate
  37343. var faceNormalx = 0.0; // facet normal x coordinate
  37344. var faceNormaly = 0.0; // facet normal y coordinate
  37345. var faceNormalz = 0.0; // facet normal z coordinate
  37346. var length = 0.0; // facet normal length before normalization
  37347. var v1x = 0; // vector1 x index in the positions array
  37348. var v1y = 0; // vector1 y index in the positions array
  37349. var v1z = 0; // vector1 z index in the positions array
  37350. var v2x = 0; // vector2 x index in the positions array
  37351. var v2y = 0; // vector2 y index in the positions array
  37352. var v2z = 0; // vector2 z index in the positions array
  37353. var v3x = 0; // vector3 x index in the positions array
  37354. var v3y = 0; // vector3 y index in the positions array
  37355. var v3z = 0; // vector3 z index in the positions array
  37356. var computeFacetNormals = false;
  37357. var computeFacetPositions = false;
  37358. var computeFacetPartitioning = false;
  37359. var computeDepthSort = false;
  37360. var faceNormalSign = 1;
  37361. var ratio = 0;
  37362. var distanceTo = null;
  37363. if (options) {
  37364. computeFacetNormals = (options.facetNormals) ? true : false;
  37365. computeFacetPositions = (options.facetPositions) ? true : false;
  37366. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37367. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37368. ratio = options.ratio || 0;
  37369. computeDepthSort = (options.depthSort) ? true : false;
  37370. distanceTo = (options.distanceTo);
  37371. if (computeDepthSort) {
  37372. if (distanceTo === undefined) {
  37373. distanceTo = BABYLON.Vector3.Zero();
  37374. }
  37375. var depthSortedFacets = options.depthSortedFacets;
  37376. }
  37377. }
  37378. // facetPartitioning reinit if needed
  37379. var xSubRatio = 0;
  37380. var ySubRatio = 0;
  37381. var zSubRatio = 0;
  37382. var subSq = 0;
  37383. if (computeFacetPartitioning && options && options.bbSize) {
  37384. var ox = 0; // X partitioning index for facet position
  37385. var oy = 0; // Y partinioning index for facet position
  37386. var oz = 0; // Z partinioning index for facet position
  37387. var b1x = 0; // X partitioning index for facet v1 vertex
  37388. var b1y = 0; // Y partitioning index for facet v1 vertex
  37389. var b1z = 0; // z partitioning index for facet v1 vertex
  37390. var b2x = 0; // X partitioning index for facet v2 vertex
  37391. var b2y = 0; // Y partitioning index for facet v2 vertex
  37392. var b2z = 0; // Z partitioning index for facet v2 vertex
  37393. var b3x = 0; // X partitioning index for facet v3 vertex
  37394. var b3y = 0; // Y partitioning index for facet v3 vertex
  37395. var b3z = 0; // Z partitioning index for facet v3 vertex
  37396. var block_idx_o = 0; // facet barycenter block index
  37397. var block_idx_v1 = 0; // v1 vertex block index
  37398. var block_idx_v2 = 0; // v2 vertex block index
  37399. var block_idx_v3 = 0; // v3 vertex block index
  37400. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37401. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37402. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37403. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37404. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37405. subSq = options.subDiv.max * options.subDiv.max;
  37406. options.facetPartitioning.length = 0;
  37407. }
  37408. // reset the normals
  37409. for (index = 0; index < positions.length; index++) {
  37410. normals[index] = 0.0;
  37411. }
  37412. // Loop : 1 indice triplet = 1 facet
  37413. var nbFaces = (indices.length / 3) | 0;
  37414. for (index = 0; index < nbFaces; index++) {
  37415. // get the indexes of the coordinates of each vertex of the facet
  37416. v1x = indices[index * 3] * 3;
  37417. v1y = v1x + 1;
  37418. v1z = v1x + 2;
  37419. v2x = indices[index * 3 + 1] * 3;
  37420. v2y = v2x + 1;
  37421. v2z = v2x + 2;
  37422. v3x = indices[index * 3 + 2] * 3;
  37423. v3y = v3x + 1;
  37424. v3z = v3x + 2;
  37425. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37426. p1p2y = positions[v1y] - positions[v2y];
  37427. p1p2z = positions[v1z] - positions[v2z];
  37428. p3p2x = positions[v3x] - positions[v2x];
  37429. p3p2y = positions[v3y] - positions[v2y];
  37430. p3p2z = positions[v3z] - positions[v2z];
  37431. // compute the face normal with the cross product
  37432. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37433. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37434. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37435. // normalize this normal and store it in the array facetData
  37436. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37437. length = (length === 0) ? 1.0 : length;
  37438. faceNormalx /= length;
  37439. faceNormaly /= length;
  37440. faceNormalz /= length;
  37441. if (computeFacetNormals && options) {
  37442. options.facetNormals[index].x = faceNormalx;
  37443. options.facetNormals[index].y = faceNormaly;
  37444. options.facetNormals[index].z = faceNormalz;
  37445. }
  37446. if (computeFacetPositions && options) {
  37447. // compute and the facet barycenter coordinates in the array facetPositions
  37448. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37449. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37450. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37451. }
  37452. if (computeFacetPartitioning && options) {
  37453. // store the facet indexes in arrays in the main facetPartitioning array :
  37454. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37455. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37456. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37457. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37458. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37459. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37460. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37461. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37462. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37463. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37464. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37465. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37466. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37467. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37468. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37469. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37470. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37471. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37472. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37473. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37474. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37475. // push each facet index in each block containing the vertex
  37476. options.facetPartitioning[block_idx_v1].push(index);
  37477. if (block_idx_v2 != block_idx_v1) {
  37478. options.facetPartitioning[block_idx_v2].push(index);
  37479. }
  37480. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37481. options.facetPartitioning[block_idx_v3].push(index);
  37482. }
  37483. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37484. options.facetPartitioning[block_idx_o].push(index);
  37485. }
  37486. }
  37487. if (computeDepthSort && options && options.facetPositions) {
  37488. var dsf = depthSortedFacets[index];
  37489. dsf.ind = index * 3;
  37490. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  37491. }
  37492. // compute the normals anyway
  37493. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37494. normals[v1y] += faceNormaly;
  37495. normals[v1z] += faceNormalz;
  37496. normals[v2x] += faceNormalx;
  37497. normals[v2y] += faceNormaly;
  37498. normals[v2z] += faceNormalz;
  37499. normals[v3x] += faceNormalx;
  37500. normals[v3y] += faceNormaly;
  37501. normals[v3z] += faceNormalz;
  37502. }
  37503. // last normalization of each normal
  37504. for (index = 0; index < normals.length / 3; index++) {
  37505. faceNormalx = normals[index * 3];
  37506. faceNormaly = normals[index * 3 + 1];
  37507. faceNormalz = normals[index * 3 + 2];
  37508. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37509. length = (length === 0) ? 1.0 : length;
  37510. faceNormalx /= length;
  37511. faceNormaly /= length;
  37512. faceNormalz /= length;
  37513. normals[index * 3] = faceNormalx;
  37514. normals[index * 3 + 1] = faceNormaly;
  37515. normals[index * 3 + 2] = faceNormalz;
  37516. }
  37517. };
  37518. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  37519. var li = indices.length;
  37520. var ln = normals.length;
  37521. var i;
  37522. var n;
  37523. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37524. switch (sideOrientation) {
  37525. case BABYLON.Mesh.FRONTSIDE:
  37526. // nothing changed
  37527. break;
  37528. case BABYLON.Mesh.BACKSIDE:
  37529. var tmp;
  37530. // indices
  37531. for (i = 0; i < li; i += 3) {
  37532. tmp = indices[i];
  37533. indices[i] = indices[i + 2];
  37534. indices[i + 2] = tmp;
  37535. }
  37536. // normals
  37537. for (n = 0; n < ln; n++) {
  37538. normals[n] = -normals[n];
  37539. }
  37540. break;
  37541. case BABYLON.Mesh.DOUBLESIDE:
  37542. // positions
  37543. var lp = positions.length;
  37544. var l = lp / 3;
  37545. for (var p = 0; p < lp; p++) {
  37546. positions[lp + p] = positions[p];
  37547. }
  37548. // indices
  37549. for (i = 0; i < li; i += 3) {
  37550. indices[i + li] = indices[i + 2] + l;
  37551. indices[i + 1 + li] = indices[i + 1] + l;
  37552. indices[i + 2 + li] = indices[i] + l;
  37553. }
  37554. // normals
  37555. for (n = 0; n < ln; n++) {
  37556. normals[ln + n] = -normals[n];
  37557. }
  37558. // uvs
  37559. var lu = uvs.length;
  37560. var u = 0;
  37561. for (u = 0; u < lu; u++) {
  37562. uvs[u + lu] = uvs[u];
  37563. }
  37564. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37565. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37566. u = 0;
  37567. for (i = 0; i < lu / 2; i++) {
  37568. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  37569. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  37570. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  37571. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  37572. u += 2;
  37573. }
  37574. break;
  37575. }
  37576. };
  37577. /**
  37578. * Creates a new VertexData from the imported parameters.
  37579. */
  37580. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  37581. var vertexData = new VertexData();
  37582. // positions
  37583. var positions = parsedVertexData.positions;
  37584. if (positions) {
  37585. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  37586. }
  37587. // normals
  37588. var normals = parsedVertexData.normals;
  37589. if (normals) {
  37590. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  37591. }
  37592. // tangents
  37593. var tangents = parsedVertexData.tangents;
  37594. if (tangents) {
  37595. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  37596. }
  37597. // uvs
  37598. var uvs = parsedVertexData.uvs;
  37599. if (uvs) {
  37600. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  37601. }
  37602. // uv2s
  37603. var uv2s = parsedVertexData.uv2s;
  37604. if (uv2s) {
  37605. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  37606. }
  37607. // uv3s
  37608. var uv3s = parsedVertexData.uv3s;
  37609. if (uv3s) {
  37610. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  37611. }
  37612. // uv4s
  37613. var uv4s = parsedVertexData.uv4s;
  37614. if (uv4s) {
  37615. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  37616. }
  37617. // uv5s
  37618. var uv5s = parsedVertexData.uv5s;
  37619. if (uv5s) {
  37620. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  37621. }
  37622. // uv6s
  37623. var uv6s = parsedVertexData.uv6s;
  37624. if (uv6s) {
  37625. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  37626. }
  37627. // colors
  37628. var colors = parsedVertexData.colors;
  37629. if (colors) {
  37630. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  37631. }
  37632. // matricesIndices
  37633. var matricesIndices = parsedVertexData.matricesIndices;
  37634. if (matricesIndices) {
  37635. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  37636. }
  37637. // matricesWeights
  37638. var matricesWeights = parsedVertexData.matricesWeights;
  37639. if (matricesWeights) {
  37640. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  37641. }
  37642. // indices
  37643. var indices = parsedVertexData.indices;
  37644. if (indices) {
  37645. vertexData.indices = indices;
  37646. }
  37647. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  37648. };
  37649. return VertexData;
  37650. }());
  37651. BABYLON.VertexData = VertexData;
  37652. })(BABYLON || (BABYLON = {}));
  37653. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  37654. "use strict";
  37655. var BABYLON;
  37656. (function (BABYLON) {
  37657. /**
  37658. * Class used to store geometry data (vertex buffers + index buffer)
  37659. */
  37660. var Geometry = /** @class */ (function () {
  37661. /**
  37662. * Creates a new geometry
  37663. * @param id defines the unique ID
  37664. * @param scene defines the hosting scene
  37665. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  37666. * @param updatable defines if geometry must be updatable (false by default)
  37667. * @param mesh defines the mesh that will be associated with the geometry
  37668. */
  37669. function Geometry(id, scene, vertexData, updatable, mesh) {
  37670. if (updatable === void 0) { updatable = false; }
  37671. if (mesh === void 0) { mesh = null; }
  37672. /**
  37673. * Gets the delay loading state of the geometry (none by default which means not delayed)
  37674. */
  37675. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37676. this._totalVertices = 0;
  37677. this._isDisposed = false;
  37678. this._indexBufferIsUpdatable = false;
  37679. this.id = id;
  37680. this._engine = scene.getEngine();
  37681. this._meshes = [];
  37682. this._scene = scene;
  37683. //Init vertex buffer cache
  37684. this._vertexBuffers = {};
  37685. this._indices = [];
  37686. this._updatable = updatable;
  37687. // vertexData
  37688. if (vertexData) {
  37689. this.setAllVerticesData(vertexData, updatable);
  37690. }
  37691. else {
  37692. this._totalVertices = 0;
  37693. this._indices = [];
  37694. }
  37695. if (this._engine.getCaps().vertexArrayObject) {
  37696. this._vertexArrayObjects = {};
  37697. }
  37698. // applyToMesh
  37699. if (mesh) {
  37700. if (mesh.getClassName() === "LinesMesh") {
  37701. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  37702. this._updateExtend();
  37703. }
  37704. this.applyToMesh(mesh);
  37705. mesh.computeWorldMatrix(true);
  37706. }
  37707. }
  37708. Object.defineProperty(Geometry.prototype, "boundingBias", {
  37709. /**
  37710. * 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
  37711. */
  37712. get: function () {
  37713. return this._boundingBias;
  37714. },
  37715. /**
  37716. * 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
  37717. */
  37718. set: function (value) {
  37719. if (this._boundingBias && this._boundingBias.equals(value)) {
  37720. return;
  37721. }
  37722. this._boundingBias = value.clone();
  37723. this._updateBoundingInfo(true, null);
  37724. },
  37725. enumerable: true,
  37726. configurable: true
  37727. });
  37728. /**
  37729. * Static function used to attach a new empty geometry to a mesh
  37730. * @param mesh defines the mesh to attach the geometry to
  37731. * @returns the new {BABYLON.Geometry}
  37732. */
  37733. Geometry.CreateGeometryForMesh = function (mesh) {
  37734. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  37735. geometry.applyToMesh(mesh);
  37736. return geometry;
  37737. };
  37738. Object.defineProperty(Geometry.prototype, "extend", {
  37739. /**
  37740. * Gets the current extend of the geometry
  37741. */
  37742. get: function () {
  37743. return this._extend;
  37744. },
  37745. enumerable: true,
  37746. configurable: true
  37747. });
  37748. /**
  37749. * Gets the hosting scene
  37750. * @returns the hosting {BABYLON.Scene}
  37751. */
  37752. Geometry.prototype.getScene = function () {
  37753. return this._scene;
  37754. };
  37755. /**
  37756. * Gets the hosting engine
  37757. * @returns the hosting {BABYLON.Engine}
  37758. */
  37759. Geometry.prototype.getEngine = function () {
  37760. return this._engine;
  37761. };
  37762. /**
  37763. * Defines if the geometry is ready to use
  37764. * @returns true if the geometry is ready to be used
  37765. */
  37766. Geometry.prototype.isReady = function () {
  37767. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  37768. };
  37769. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  37770. /**
  37771. * Gets a value indicating that the geometry should not be serialized
  37772. */
  37773. get: function () {
  37774. for (var index = 0; index < this._meshes.length; index++) {
  37775. if (!this._meshes[index].doNotSerialize) {
  37776. return false;
  37777. }
  37778. }
  37779. return true;
  37780. },
  37781. enumerable: true,
  37782. configurable: true
  37783. });
  37784. /** @ignore */
  37785. Geometry.prototype._rebuild = function () {
  37786. if (this._vertexArrayObjects) {
  37787. this._vertexArrayObjects = {};
  37788. }
  37789. // Index buffer
  37790. if (this._meshes.length !== 0 && this._indices) {
  37791. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37792. }
  37793. // Vertex buffers
  37794. for (var key in this._vertexBuffers) {
  37795. var vertexBuffer = this._vertexBuffers[key];
  37796. vertexBuffer._rebuild();
  37797. }
  37798. };
  37799. /**
  37800. * Affects all gemetry data in one call
  37801. * @param vertexData defines the geometry data
  37802. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  37803. */
  37804. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37805. vertexData.applyToGeometry(this, updatable);
  37806. this.notifyUpdate();
  37807. };
  37808. /**
  37809. * Set specific vertex data
  37810. * @param kind defines the data kind (Position, normal, etc...)
  37811. * @param data defines the vertex data to use
  37812. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  37813. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  37814. */
  37815. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37816. if (updatable === void 0) { updatable = false; }
  37817. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37818. this._totalVertices = data.length / (stride || 3);
  37819. }
  37820. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  37821. this.setVerticesBuffer(buffer);
  37822. };
  37823. /**
  37824. * Removes a specific vertex data
  37825. * @param kind defines the data kind (Position, normal, etc...)
  37826. */
  37827. Geometry.prototype.removeVerticesData = function (kind) {
  37828. if (this._vertexBuffers[kind]) {
  37829. this._vertexBuffers[kind].dispose();
  37830. delete this._vertexBuffers[kind];
  37831. }
  37832. };
  37833. /**
  37834. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  37835. * @param buffer defines the vertex buffer to use
  37836. * @param totalVertices defines the total number of vertices for position kind (could be null)
  37837. */
  37838. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  37839. if (totalVertices === void 0) { totalVertices = null; }
  37840. var kind = buffer.getKind();
  37841. if (this._vertexBuffers[kind]) {
  37842. this._vertexBuffers[kind].dispose();
  37843. }
  37844. this._vertexBuffers[kind] = buffer;
  37845. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37846. if (totalVertices != null) {
  37847. this._totalVertices = totalVertices;
  37848. }
  37849. this._updateExtend();
  37850. this._resetPointsArrayCache();
  37851. var meshes = this._meshes;
  37852. var numOfMeshes = meshes.length;
  37853. for (var index = 0; index < numOfMeshes; index++) {
  37854. var mesh = meshes[index];
  37855. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37856. mesh._createGlobalSubMesh(false);
  37857. mesh.computeWorldMatrix(true);
  37858. }
  37859. }
  37860. this.notifyUpdate(kind);
  37861. if (this._vertexArrayObjects) {
  37862. this._disposeVertexArrayObjects();
  37863. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  37864. }
  37865. };
  37866. /**
  37867. * Update a specific vertex buffer
  37868. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  37869. * It will do nothing if the buffer is not updatable
  37870. * @param kind defines the data kind (Position, normal, etc...)
  37871. * @param data defines the data to use
  37872. * @param offset defines the offset in the target buffer where to store the data
  37873. */
  37874. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  37875. var vertexBuffer = this.getVertexBuffer(kind);
  37876. if (!vertexBuffer) {
  37877. return;
  37878. }
  37879. vertexBuffer.updateDirectly(data, offset);
  37880. this.notifyUpdate(kind);
  37881. };
  37882. /**
  37883. * Update a specific vertex buffer
  37884. * This function will create a new buffer if the current one is not updatable
  37885. * @param kind defines the data kind (Position, normal, etc...)
  37886. * @param data defines the data to use
  37887. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  37888. */
  37889. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  37890. if (updateExtends === void 0) { updateExtends = false; }
  37891. var vertexBuffer = this.getVertexBuffer(kind);
  37892. if (!vertexBuffer) {
  37893. return;
  37894. }
  37895. vertexBuffer.update(data);
  37896. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37897. this._updateBoundingInfo(updateExtends, data);
  37898. }
  37899. this.notifyUpdate(kind);
  37900. };
  37901. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  37902. if (updateExtends) {
  37903. this._updateExtend(data);
  37904. }
  37905. var meshes = this._meshes;
  37906. var numOfMeshes = meshes.length;
  37907. this._resetPointsArrayCache();
  37908. for (var index = 0; index < numOfMeshes; index++) {
  37909. var mesh = meshes[index];
  37910. if (updateExtends) {
  37911. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37912. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  37913. var subMesh = mesh.subMeshes[subIndex];
  37914. subMesh.refreshBoundingInfo();
  37915. }
  37916. }
  37917. }
  37918. };
  37919. /** @ignore */
  37920. Geometry.prototype._bind = function (effect, indexToBind) {
  37921. if (!effect) {
  37922. return;
  37923. }
  37924. if (indexToBind === undefined) {
  37925. indexToBind = this._indexBuffer;
  37926. }
  37927. var vbs = this.getVertexBuffers();
  37928. if (!vbs) {
  37929. return;
  37930. }
  37931. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  37932. this._engine.bindBuffers(vbs, indexToBind, effect);
  37933. return;
  37934. }
  37935. // Using VAO
  37936. if (!this._vertexArrayObjects[effect.key]) {
  37937. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  37938. }
  37939. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  37940. };
  37941. /**
  37942. * Gets total number of vertices
  37943. * @returns the total number of vertices
  37944. */
  37945. Geometry.prototype.getTotalVertices = function () {
  37946. if (!this.isReady()) {
  37947. return 0;
  37948. }
  37949. return this._totalVertices;
  37950. };
  37951. /**
  37952. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  37953. * @param kind defines the data kind (Position, normal, etc...)
  37954. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  37955. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  37956. * @returns a float array containing vertex data
  37957. */
  37958. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  37959. var vertexBuffer = this.getVertexBuffer(kind);
  37960. if (!vertexBuffer) {
  37961. return null;
  37962. }
  37963. var data = vertexBuffer.getData();
  37964. if (!data) {
  37965. return null;
  37966. }
  37967. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  37968. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  37969. var count = this._totalVertices * defaultStride;
  37970. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  37971. var copy_1 = new Array(count);
  37972. vertexBuffer.forEach(count, function (value, index) {
  37973. copy_1[index] = value;
  37974. });
  37975. return copy_1;
  37976. }
  37977. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  37978. if (data instanceof Array) {
  37979. var offset = vertexBuffer.byteOffset / 4;
  37980. return BABYLON.Tools.Slice(data, offset, offset + count);
  37981. }
  37982. else if (data instanceof ArrayBuffer) {
  37983. return new Float32Array(data, vertexBuffer.byteOffset, count);
  37984. }
  37985. else {
  37986. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  37987. }
  37988. }
  37989. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  37990. return BABYLON.Tools.Slice(data);
  37991. }
  37992. return data;
  37993. };
  37994. /**
  37995. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  37996. * @param kind defines the data kind (Position, normal, etc...)
  37997. * @returns true if the vertex buffer with the specified kind is updatable
  37998. */
  37999. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38000. var vb = this._vertexBuffers[kind];
  38001. if (!vb) {
  38002. return false;
  38003. }
  38004. return vb.isUpdatable();
  38005. };
  38006. /**
  38007. * Gets a specific vertex buffer
  38008. * @param kind defines the data kind (Position, normal, etc...)
  38009. * @returns a {BABYLON.VertexBuffer}
  38010. */
  38011. Geometry.prototype.getVertexBuffer = function (kind) {
  38012. if (!this.isReady()) {
  38013. return null;
  38014. }
  38015. return this._vertexBuffers[kind];
  38016. };
  38017. /**
  38018. * Returns all vertex buffers
  38019. * @return an object holding all vertex buffers indexed by kind
  38020. */
  38021. Geometry.prototype.getVertexBuffers = function () {
  38022. if (!this.isReady()) {
  38023. return null;
  38024. }
  38025. return this._vertexBuffers;
  38026. };
  38027. /**
  38028. * Gets a boolean indicating if specific vertex buffer is present
  38029. * @param kind defines the data kind (Position, normal, etc...)
  38030. * @returns true if data is present
  38031. */
  38032. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38033. if (!this._vertexBuffers) {
  38034. if (this._delayInfo) {
  38035. return this._delayInfo.indexOf(kind) !== -1;
  38036. }
  38037. return false;
  38038. }
  38039. return this._vertexBuffers[kind] !== undefined;
  38040. };
  38041. /**
  38042. * Gets a list of all attached data kinds (Position, normal, etc...)
  38043. * @returns a list of string containing all kinds
  38044. */
  38045. Geometry.prototype.getVerticesDataKinds = function () {
  38046. var result = [];
  38047. var kind;
  38048. if (!this._vertexBuffers && this._delayInfo) {
  38049. for (kind in this._delayInfo) {
  38050. result.push(kind);
  38051. }
  38052. }
  38053. else {
  38054. for (kind in this._vertexBuffers) {
  38055. result.push(kind);
  38056. }
  38057. }
  38058. return result;
  38059. };
  38060. /**
  38061. * Update index buffer
  38062. * @param indices defines the indices to store in the index buffer
  38063. * @param offset defines the offset in the target buffer where to store the data
  38064. */
  38065. Geometry.prototype.updateIndices = function (indices, offset) {
  38066. if (!this._indexBuffer) {
  38067. return;
  38068. }
  38069. if (!this._indexBufferIsUpdatable) {
  38070. this.setIndices(indices, null, true);
  38071. }
  38072. else {
  38073. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38074. }
  38075. };
  38076. /**
  38077. * Creates a new index buffer
  38078. * @param indices defines the indices to store in the index buffer
  38079. * @param totalVertices defines the total number of vertices (could be null)
  38080. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38081. */
  38082. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38083. if (totalVertices === void 0) { totalVertices = null; }
  38084. if (updatable === void 0) { updatable = false; }
  38085. if (this._indexBuffer) {
  38086. this._engine._releaseBuffer(this._indexBuffer);
  38087. }
  38088. this._disposeVertexArrayObjects();
  38089. this._indices = indices;
  38090. this._indexBufferIsUpdatable = updatable;
  38091. if (this._meshes.length !== 0 && this._indices) {
  38092. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38093. }
  38094. if (totalVertices != undefined) {
  38095. this._totalVertices = totalVertices;
  38096. }
  38097. var meshes = this._meshes;
  38098. var numOfMeshes = meshes.length;
  38099. for (var index = 0; index < numOfMeshes; index++) {
  38100. meshes[index]._createGlobalSubMesh(true);
  38101. }
  38102. this.notifyUpdate();
  38103. };
  38104. /**
  38105. * Return the total number of indices
  38106. * @returns the total number of indices
  38107. */
  38108. Geometry.prototype.getTotalIndices = function () {
  38109. if (!this.isReady()) {
  38110. return 0;
  38111. }
  38112. return this._indices.length;
  38113. };
  38114. /**
  38115. * Gets the index buffer array
  38116. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38117. * @returns the index buffer array
  38118. */
  38119. Geometry.prototype.getIndices = function (copyWhenShared) {
  38120. if (!this.isReady()) {
  38121. return null;
  38122. }
  38123. var orig = this._indices;
  38124. if (!copyWhenShared || this._meshes.length === 1) {
  38125. return orig;
  38126. }
  38127. else {
  38128. var len = orig.length;
  38129. var copy = [];
  38130. for (var i = 0; i < len; i++) {
  38131. copy.push(orig[i]);
  38132. }
  38133. return copy;
  38134. }
  38135. };
  38136. /**
  38137. * Gets the index buffer
  38138. * @return the index buffer
  38139. */
  38140. Geometry.prototype.getIndexBuffer = function () {
  38141. if (!this.isReady()) {
  38142. return null;
  38143. }
  38144. return this._indexBuffer;
  38145. };
  38146. /** @ignore */
  38147. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38148. if (effect === void 0) { effect = null; }
  38149. if (!effect || !this._vertexArrayObjects) {
  38150. return;
  38151. }
  38152. if (this._vertexArrayObjects[effect.key]) {
  38153. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38154. delete this._vertexArrayObjects[effect.key];
  38155. }
  38156. };
  38157. /**
  38158. * Release the associated resources for a specific mesh
  38159. * @param mesh defines the source mesh
  38160. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38161. */
  38162. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38163. var meshes = this._meshes;
  38164. var index = meshes.indexOf(mesh);
  38165. if (index === -1) {
  38166. return;
  38167. }
  38168. meshes.splice(index, 1);
  38169. mesh._geometry = null;
  38170. if (meshes.length === 0 && shouldDispose) {
  38171. this.dispose();
  38172. }
  38173. };
  38174. /**
  38175. * Apply current geometry to a given mesh
  38176. * @param mesh defines the mesh to apply geometry to
  38177. */
  38178. Geometry.prototype.applyToMesh = function (mesh) {
  38179. if (mesh._geometry === this) {
  38180. return;
  38181. }
  38182. var previousGeometry = mesh._geometry;
  38183. if (previousGeometry) {
  38184. previousGeometry.releaseForMesh(mesh);
  38185. }
  38186. var meshes = this._meshes;
  38187. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38188. mesh._geometry = this;
  38189. this._scene.pushGeometry(this);
  38190. meshes.push(mesh);
  38191. if (this.isReady()) {
  38192. this._applyToMesh(mesh);
  38193. }
  38194. else {
  38195. mesh._boundingInfo = this._boundingInfo;
  38196. }
  38197. };
  38198. Geometry.prototype._updateExtend = function (data) {
  38199. if (data === void 0) { data = null; }
  38200. if (!data) {
  38201. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38202. }
  38203. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38204. };
  38205. Geometry.prototype._applyToMesh = function (mesh) {
  38206. var numOfMeshes = this._meshes.length;
  38207. // vertexBuffers
  38208. for (var kind in this._vertexBuffers) {
  38209. if (numOfMeshes === 1) {
  38210. this._vertexBuffers[kind].create();
  38211. }
  38212. var buffer = this._vertexBuffers[kind].getBuffer();
  38213. if (buffer)
  38214. buffer.references = numOfMeshes;
  38215. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38216. if (!this._extend) {
  38217. this._updateExtend();
  38218. }
  38219. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38220. mesh._createGlobalSubMesh(false);
  38221. //bounding info was just created again, world matrix should be applied again.
  38222. mesh._updateBoundingInfo();
  38223. }
  38224. }
  38225. // indexBuffer
  38226. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38227. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38228. }
  38229. if (this._indexBuffer) {
  38230. this._indexBuffer.references = numOfMeshes;
  38231. }
  38232. };
  38233. Geometry.prototype.notifyUpdate = function (kind) {
  38234. if (this.onGeometryUpdated) {
  38235. this.onGeometryUpdated(this, kind);
  38236. }
  38237. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38238. var mesh = _a[_i];
  38239. mesh._markSubMeshesAsAttributesDirty();
  38240. }
  38241. };
  38242. /**
  38243. * Load the geometry if it was flagged as delay loaded
  38244. * @param scene defines the hosting scene
  38245. * @param onLoaded defines a callback called when the geometry is loaded
  38246. */
  38247. Geometry.prototype.load = function (scene, onLoaded) {
  38248. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38249. return;
  38250. }
  38251. if (this.isReady()) {
  38252. if (onLoaded) {
  38253. onLoaded();
  38254. }
  38255. return;
  38256. }
  38257. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38258. this._queueLoad(scene, onLoaded);
  38259. };
  38260. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38261. var _this = this;
  38262. if (!this.delayLoadingFile) {
  38263. return;
  38264. }
  38265. scene._addPendingData(this);
  38266. scene._loadFile(this.delayLoadingFile, function (data) {
  38267. if (!_this._delayLoadingFunction) {
  38268. return;
  38269. }
  38270. _this._delayLoadingFunction(JSON.parse(data), _this);
  38271. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38272. _this._delayInfo = [];
  38273. scene._removePendingData(_this);
  38274. var meshes = _this._meshes;
  38275. var numOfMeshes = meshes.length;
  38276. for (var index = 0; index < numOfMeshes; index++) {
  38277. _this._applyToMesh(meshes[index]);
  38278. }
  38279. if (onLoaded) {
  38280. onLoaded();
  38281. }
  38282. }, undefined, true);
  38283. };
  38284. /**
  38285. * Invert the geometry to move from a right handed system to a left handed one.
  38286. */
  38287. Geometry.prototype.toLeftHanded = function () {
  38288. // Flip faces
  38289. var tIndices = this.getIndices(false);
  38290. if (tIndices != null && tIndices.length > 0) {
  38291. for (var i = 0; i < tIndices.length; i += 3) {
  38292. var tTemp = tIndices[i + 0];
  38293. tIndices[i + 0] = tIndices[i + 2];
  38294. tIndices[i + 2] = tTemp;
  38295. }
  38296. this.setIndices(tIndices);
  38297. }
  38298. // Negate position.z
  38299. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38300. if (tPositions != null && tPositions.length > 0) {
  38301. for (var i = 0; i < tPositions.length; i += 3) {
  38302. tPositions[i + 2] = -tPositions[i + 2];
  38303. }
  38304. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38305. }
  38306. // Negate normal.z
  38307. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38308. if (tNormals != null && tNormals.length > 0) {
  38309. for (var i = 0; i < tNormals.length; i += 3) {
  38310. tNormals[i + 2] = -tNormals[i + 2];
  38311. }
  38312. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38313. }
  38314. };
  38315. // Cache
  38316. /** @ignore */
  38317. Geometry.prototype._resetPointsArrayCache = function () {
  38318. this._positions = null;
  38319. };
  38320. /** @ignore */
  38321. Geometry.prototype._generatePointsArray = function () {
  38322. if (this._positions)
  38323. return true;
  38324. this._positions = [];
  38325. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38326. if (!data) {
  38327. return false;
  38328. }
  38329. for (var index = 0; index < data.length; index += 3) {
  38330. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38331. }
  38332. return true;
  38333. };
  38334. /**
  38335. * Gets a value indicating if the geometry is disposed
  38336. * @returns true if the geometry was disposed
  38337. */
  38338. Geometry.prototype.isDisposed = function () {
  38339. return this._isDisposed;
  38340. };
  38341. Geometry.prototype._disposeVertexArrayObjects = function () {
  38342. if (this._vertexArrayObjects) {
  38343. for (var kind in this._vertexArrayObjects) {
  38344. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38345. }
  38346. this._vertexArrayObjects = {};
  38347. }
  38348. };
  38349. /**
  38350. * Free all associated resources
  38351. */
  38352. Geometry.prototype.dispose = function () {
  38353. var meshes = this._meshes;
  38354. var numOfMeshes = meshes.length;
  38355. var index;
  38356. for (index = 0; index < numOfMeshes; index++) {
  38357. this.releaseForMesh(meshes[index]);
  38358. }
  38359. this._meshes = [];
  38360. this._disposeVertexArrayObjects();
  38361. for (var kind in this._vertexBuffers) {
  38362. this._vertexBuffers[kind].dispose();
  38363. }
  38364. this._vertexBuffers = {};
  38365. this._totalVertices = 0;
  38366. if (this._indexBuffer) {
  38367. this._engine._releaseBuffer(this._indexBuffer);
  38368. }
  38369. this._indexBuffer = null;
  38370. this._indices = [];
  38371. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38372. this.delayLoadingFile = null;
  38373. this._delayLoadingFunction = null;
  38374. this._delayInfo = [];
  38375. this._boundingInfo = null;
  38376. this._scene.removeGeometry(this);
  38377. this._isDisposed = true;
  38378. };
  38379. /**
  38380. * Clone the current geometry into a new geometry
  38381. * @param id defines the unique ID of the new geometry
  38382. * @returns a new geometry object
  38383. */
  38384. Geometry.prototype.copy = function (id) {
  38385. var vertexData = new BABYLON.VertexData();
  38386. vertexData.indices = [];
  38387. var indices = this.getIndices();
  38388. if (indices) {
  38389. for (var index = 0; index < indices.length; index++) {
  38390. vertexData.indices.push(indices[index]);
  38391. }
  38392. }
  38393. var updatable = false;
  38394. var stopChecking = false;
  38395. var kind;
  38396. for (kind in this._vertexBuffers) {
  38397. // using slice() to make a copy of the array and not just reference it
  38398. var data = this.getVerticesData(kind);
  38399. if (data instanceof Float32Array) {
  38400. vertexData.set(new Float32Array(data), kind);
  38401. }
  38402. else {
  38403. vertexData.set(data.slice(0), kind);
  38404. }
  38405. if (!stopChecking) {
  38406. var vb = this.getVertexBuffer(kind);
  38407. if (vb) {
  38408. updatable = vb.isUpdatable();
  38409. stopChecking = !updatable;
  38410. }
  38411. }
  38412. }
  38413. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38414. geometry.delayLoadState = this.delayLoadState;
  38415. geometry.delayLoadingFile = this.delayLoadingFile;
  38416. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38417. for (kind in this._delayInfo) {
  38418. geometry._delayInfo = geometry._delayInfo || [];
  38419. geometry._delayInfo.push(kind);
  38420. }
  38421. // Bounding info
  38422. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38423. return geometry;
  38424. };
  38425. /**
  38426. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38427. * @return a JSON representation of the current geometry data (without the vertices data)
  38428. */
  38429. Geometry.prototype.serialize = function () {
  38430. var serializationObject = {};
  38431. serializationObject.id = this.id;
  38432. serializationObject.updatable = this._updatable;
  38433. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38434. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38435. }
  38436. return serializationObject;
  38437. };
  38438. Geometry.prototype.toNumberArray = function (origin) {
  38439. if (Array.isArray(origin)) {
  38440. return origin;
  38441. }
  38442. else {
  38443. return Array.prototype.slice.call(origin);
  38444. }
  38445. };
  38446. /**
  38447. * Serialize all vertices data into a JSON oject
  38448. * @returns a JSON representation of the current geometry data
  38449. */
  38450. Geometry.prototype.serializeVerticeData = function () {
  38451. var serializationObject = this.serialize();
  38452. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38453. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38454. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38455. serializationObject.positions._updatable = true;
  38456. }
  38457. }
  38458. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38459. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38460. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38461. serializationObject.normals._updatable = true;
  38462. }
  38463. }
  38464. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38465. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38466. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38467. serializationObject.tangets._updatable = true;
  38468. }
  38469. }
  38470. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38471. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38472. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38473. serializationObject.uvs._updatable = true;
  38474. }
  38475. }
  38476. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38477. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38478. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38479. serializationObject.uv2s._updatable = true;
  38480. }
  38481. }
  38482. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38483. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  38484. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  38485. serializationObject.uv3s._updatable = true;
  38486. }
  38487. }
  38488. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38489. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  38490. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  38491. serializationObject.uv4s._updatable = true;
  38492. }
  38493. }
  38494. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38495. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  38496. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  38497. serializationObject.uv5s._updatable = true;
  38498. }
  38499. }
  38500. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38501. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  38502. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  38503. serializationObject.uv6s._updatable = true;
  38504. }
  38505. }
  38506. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38507. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  38508. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  38509. serializationObject.colors._updatable = true;
  38510. }
  38511. }
  38512. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38513. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  38514. serializationObject.matricesIndices._isExpanded = true;
  38515. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38516. serializationObject.matricesIndices._updatable = true;
  38517. }
  38518. }
  38519. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38520. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  38521. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38522. serializationObject.matricesWeights._updatable = true;
  38523. }
  38524. }
  38525. serializationObject.indices = this.toNumberArray(this.getIndices());
  38526. return serializationObject;
  38527. };
  38528. // Statics
  38529. /**
  38530. * Extracts a clone of a mesh geometry
  38531. * @param mesh defines the source mesh
  38532. * @param id defines the unique ID of the new geometry object
  38533. * @returns the new geometry object
  38534. */
  38535. Geometry.ExtractFromMesh = function (mesh, id) {
  38536. var geometry = mesh._geometry;
  38537. if (!geometry) {
  38538. return null;
  38539. }
  38540. return geometry.copy(id);
  38541. };
  38542. /**
  38543. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  38544. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  38545. * Be aware Math.random() could cause collisions, but:
  38546. * "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"
  38547. * @returns a string containing a new GUID
  38548. */
  38549. Geometry.RandomId = function () {
  38550. return BABYLON.Tools.RandomId();
  38551. };
  38552. /** @ignore */
  38553. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  38554. var scene = mesh.getScene();
  38555. // Geometry
  38556. var geometryId = parsedGeometry.geometryId;
  38557. if (geometryId) {
  38558. var geometry = scene.getGeometryByID(geometryId);
  38559. if (geometry) {
  38560. geometry.applyToMesh(mesh);
  38561. }
  38562. }
  38563. else if (parsedGeometry instanceof ArrayBuffer) {
  38564. var binaryInfo = mesh._binaryInfo;
  38565. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  38566. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  38567. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  38568. }
  38569. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  38570. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  38571. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  38572. }
  38573. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  38574. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  38575. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  38576. }
  38577. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  38578. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  38579. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  38580. }
  38581. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  38582. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  38583. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  38584. }
  38585. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  38586. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  38587. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  38588. }
  38589. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  38590. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  38591. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  38592. }
  38593. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  38594. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  38595. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  38596. }
  38597. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  38598. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  38599. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  38600. }
  38601. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  38602. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  38603. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  38604. }
  38605. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  38606. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  38607. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  38608. }
  38609. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  38610. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  38611. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  38612. }
  38613. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  38614. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  38615. mesh.setIndices(indicesData, null);
  38616. }
  38617. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  38618. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  38619. mesh.subMeshes = [];
  38620. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  38621. var materialIndex = subMeshesData[(i * 5) + 0];
  38622. var verticesStart = subMeshesData[(i * 5) + 1];
  38623. var verticesCount = subMeshesData[(i * 5) + 2];
  38624. var indexStart = subMeshesData[(i * 5) + 3];
  38625. var indexCount = subMeshesData[(i * 5) + 4];
  38626. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  38627. }
  38628. }
  38629. }
  38630. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  38631. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  38632. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  38633. if (parsedGeometry.tangents) {
  38634. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  38635. }
  38636. if (parsedGeometry.uvs) {
  38637. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  38638. }
  38639. if (parsedGeometry.uvs2) {
  38640. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  38641. }
  38642. if (parsedGeometry.uvs3) {
  38643. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  38644. }
  38645. if (parsedGeometry.uvs4) {
  38646. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  38647. }
  38648. if (parsedGeometry.uvs5) {
  38649. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  38650. }
  38651. if (parsedGeometry.uvs6) {
  38652. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  38653. }
  38654. if (parsedGeometry.colors) {
  38655. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  38656. }
  38657. if (parsedGeometry.matricesIndices) {
  38658. if (!parsedGeometry.matricesIndices._isExpanded) {
  38659. var floatIndices = [];
  38660. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  38661. var matricesIndex = parsedGeometry.matricesIndices[i];
  38662. floatIndices.push(matricesIndex & 0x000000FF);
  38663. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38664. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38665. floatIndices.push(matricesIndex >> 24);
  38666. }
  38667. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  38668. }
  38669. else {
  38670. delete parsedGeometry.matricesIndices._isExpanded;
  38671. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  38672. }
  38673. }
  38674. if (parsedGeometry.matricesIndicesExtra) {
  38675. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  38676. var floatIndices = [];
  38677. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  38678. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  38679. floatIndices.push(matricesIndex & 0x000000FF);
  38680. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38681. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38682. floatIndices.push(matricesIndex >> 24);
  38683. }
  38684. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  38685. }
  38686. else {
  38687. delete parsedGeometry.matricesIndices._isExpanded;
  38688. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  38689. }
  38690. }
  38691. if (parsedGeometry.matricesWeights) {
  38692. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  38693. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  38694. }
  38695. if (parsedGeometry.matricesWeightsExtra) {
  38696. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  38697. }
  38698. mesh.setIndices(parsedGeometry.indices, null);
  38699. }
  38700. // SubMeshes
  38701. if (parsedGeometry.subMeshes) {
  38702. mesh.subMeshes = [];
  38703. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  38704. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  38705. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  38706. }
  38707. }
  38708. // Flat shading
  38709. if (mesh._shouldGenerateFlatShading) {
  38710. mesh.convertToFlatShadedMesh();
  38711. delete mesh._shouldGenerateFlatShading;
  38712. }
  38713. // Update
  38714. mesh.computeWorldMatrix(true);
  38715. // Octree
  38716. var sceneOctree = scene.selectionOctree;
  38717. if (sceneOctree !== undefined && sceneOctree !== null) {
  38718. sceneOctree.addMesh(mesh);
  38719. }
  38720. };
  38721. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  38722. var epsilon = 1e-3;
  38723. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  38724. return;
  38725. }
  38726. var noInfluenceBoneIndex = 0.0;
  38727. if (parsedGeometry.skeletonId > -1) {
  38728. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  38729. if (!skeleton) {
  38730. return;
  38731. }
  38732. noInfluenceBoneIndex = skeleton.bones.length;
  38733. }
  38734. else {
  38735. return;
  38736. }
  38737. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  38738. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38739. var matricesWeights = parsedGeometry.matricesWeights;
  38740. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  38741. var influencers = parsedGeometry.numBoneInfluencer;
  38742. var size = matricesWeights.length;
  38743. for (var i = 0; i < size; i += 4) {
  38744. var weight = 0.0;
  38745. var firstZeroWeight = -1;
  38746. for (var j = 0; j < 4; j++) {
  38747. var w = matricesWeights[i + j];
  38748. weight += w;
  38749. if (w < epsilon && firstZeroWeight < 0) {
  38750. firstZeroWeight = j;
  38751. }
  38752. }
  38753. if (matricesWeightsExtra) {
  38754. for (var j = 0; j < 4; j++) {
  38755. var w = matricesWeightsExtra[i + j];
  38756. weight += w;
  38757. if (w < epsilon && firstZeroWeight < 0) {
  38758. firstZeroWeight = j + 4;
  38759. }
  38760. }
  38761. }
  38762. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  38763. firstZeroWeight = influencers - 1;
  38764. }
  38765. if (weight > epsilon) {
  38766. var mweight = 1.0 / weight;
  38767. for (var j = 0; j < 4; j++) {
  38768. matricesWeights[i + j] *= mweight;
  38769. }
  38770. if (matricesWeightsExtra) {
  38771. for (var j = 0; j < 4; j++) {
  38772. matricesWeightsExtra[i + j] *= mweight;
  38773. }
  38774. }
  38775. }
  38776. else {
  38777. if (firstZeroWeight >= 4) {
  38778. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  38779. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  38780. }
  38781. else {
  38782. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  38783. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  38784. }
  38785. }
  38786. }
  38787. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  38788. if (parsedGeometry.matricesWeightsExtra) {
  38789. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  38790. }
  38791. };
  38792. /**
  38793. * Create a new geometry from persisted data (Using .babylon file format)
  38794. * @param parsedVertexData defines the persisted data
  38795. * @param scene defines the hosting scene
  38796. * @param rootUrl defines the root url to use to load assets (like delayed data)
  38797. * @returns the new geometry object
  38798. */
  38799. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  38800. if (scene.getGeometryByID(parsedVertexData.id)) {
  38801. return null; // null since geometry could be something else than a box...
  38802. }
  38803. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  38804. if (BABYLON.Tags) {
  38805. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  38806. }
  38807. if (parsedVertexData.delayLoadingFile) {
  38808. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38809. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  38810. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  38811. geometry._delayInfo = [];
  38812. if (parsedVertexData.hasUVs) {
  38813. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  38814. }
  38815. if (parsedVertexData.hasUVs2) {
  38816. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  38817. }
  38818. if (parsedVertexData.hasUVs3) {
  38819. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  38820. }
  38821. if (parsedVertexData.hasUVs4) {
  38822. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  38823. }
  38824. if (parsedVertexData.hasUVs5) {
  38825. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  38826. }
  38827. if (parsedVertexData.hasUVs6) {
  38828. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  38829. }
  38830. if (parsedVertexData.hasColors) {
  38831. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  38832. }
  38833. if (parsedVertexData.hasMatricesIndices) {
  38834. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38835. }
  38836. if (parsedVertexData.hasMatricesWeights) {
  38837. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38838. }
  38839. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  38840. }
  38841. else {
  38842. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  38843. }
  38844. scene.pushGeometry(geometry, true);
  38845. return geometry;
  38846. };
  38847. return Geometry;
  38848. }());
  38849. BABYLON.Geometry = Geometry;
  38850. // Primitives
  38851. /// Abstract class
  38852. /**
  38853. * Abstract class used to provide common services for all typed geometries
  38854. */
  38855. var _PrimitiveGeometry = /** @class */ (function (_super) {
  38856. __extends(_PrimitiveGeometry, _super);
  38857. /**
  38858. * Creates a new typed geometry
  38859. * @param id defines the unique ID of the geometry
  38860. * @param scene defines the hosting scene
  38861. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38862. * @param mesh defines the hosting mesh (can be null)
  38863. */
  38864. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  38865. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  38866. if (mesh === void 0) { mesh = null; }
  38867. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  38868. _this._canBeRegenerated = _canBeRegenerated;
  38869. _this._beingRegenerated = true;
  38870. _this.regenerate();
  38871. _this._beingRegenerated = false;
  38872. return _this;
  38873. }
  38874. /**
  38875. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  38876. * @returns true if the geometry can be regenerated
  38877. */
  38878. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  38879. return this._canBeRegenerated;
  38880. };
  38881. /**
  38882. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  38883. */
  38884. _PrimitiveGeometry.prototype.regenerate = function () {
  38885. if (!this._canBeRegenerated) {
  38886. return;
  38887. }
  38888. this._beingRegenerated = true;
  38889. this.setAllVerticesData(this._regenerateVertexData(), false);
  38890. this._beingRegenerated = false;
  38891. };
  38892. /**
  38893. * Clone the geometry
  38894. * @param id defines the unique ID of the new geometry
  38895. * @returns the new geometry
  38896. */
  38897. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  38898. return _super.prototype.copy.call(this, id);
  38899. };
  38900. // overrides
  38901. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38902. if (!this._beingRegenerated) {
  38903. return;
  38904. }
  38905. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  38906. };
  38907. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  38908. if (!this._beingRegenerated) {
  38909. return;
  38910. }
  38911. _super.prototype.setVerticesData.call(this, kind, data, false);
  38912. };
  38913. // to override
  38914. /** @ignore */
  38915. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  38916. throw new Error("Abstract method");
  38917. };
  38918. _PrimitiveGeometry.prototype.copy = function (id) {
  38919. throw new Error("Must be overriden in sub-classes.");
  38920. };
  38921. _PrimitiveGeometry.prototype.serialize = function () {
  38922. var serializationObject = _super.prototype.serialize.call(this);
  38923. serializationObject.canBeRegenerated = this.canBeRegenerated();
  38924. return serializationObject;
  38925. };
  38926. return _PrimitiveGeometry;
  38927. }(Geometry));
  38928. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  38929. /**
  38930. * Creates a ribbon geometry
  38931. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  38932. */
  38933. var RibbonGeometry = /** @class */ (function (_super) {
  38934. __extends(RibbonGeometry, _super);
  38935. /**
  38936. * Creates a ribbon geometry
  38937. * @param id defines the unique ID of the geometry
  38938. * @param scene defines the hosting scene
  38939. * @param pathArray defines the array of paths to use
  38940. * @param closeArray defines if the last path and the first path must be joined
  38941. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  38942. * @param offset defines the offset between points
  38943. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38944. * @param mesh defines the hosting mesh (can be null)
  38945. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38946. */
  38947. function RibbonGeometry(id, scene,
  38948. /**
  38949. * Defines the array of paths to use
  38950. */
  38951. pathArray,
  38952. /**
  38953. * Defines if the last and first points of each path in your pathArray must be joined
  38954. */
  38955. closeArray,
  38956. /**
  38957. * Defines if the last and first points of each path in your pathArray must be joined
  38958. */
  38959. closePath,
  38960. /**
  38961. * Defines the offset between points
  38962. */
  38963. offset, canBeRegenerated, mesh,
  38964. /**
  38965. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38966. */
  38967. side) {
  38968. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38969. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38970. _this.pathArray = pathArray;
  38971. _this.closeArray = closeArray;
  38972. _this.closePath = closePath;
  38973. _this.offset = offset;
  38974. _this.side = side;
  38975. return _this;
  38976. }
  38977. /** @ignore */
  38978. RibbonGeometry.prototype._regenerateVertexData = function () {
  38979. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  38980. };
  38981. RibbonGeometry.prototype.copy = function (id) {
  38982. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  38983. };
  38984. return RibbonGeometry;
  38985. }(_PrimitiveGeometry));
  38986. BABYLON.RibbonGeometry = RibbonGeometry;
  38987. /**
  38988. * Creates a box geometry
  38989. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  38990. */
  38991. var BoxGeometry = /** @class */ (function (_super) {
  38992. __extends(BoxGeometry, _super);
  38993. /**
  38994. * Creates a box geometry
  38995. * @param id defines the unique ID of the geometry
  38996. * @param scene defines the hosting scene
  38997. * @param size defines the zise of the box (width, height and depth are the same)
  38998. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38999. * @param mesh defines the hosting mesh (can be null)
  39000. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39001. */
  39002. function BoxGeometry(id, scene,
  39003. /**
  39004. * Defines the zise of the box (width, height and depth are the same)
  39005. */
  39006. size, canBeRegenerated, mesh,
  39007. /**
  39008. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39009. */
  39010. side) {
  39011. if (mesh === void 0) { mesh = null; }
  39012. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39013. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39014. _this.size = size;
  39015. _this.side = side;
  39016. return _this;
  39017. }
  39018. BoxGeometry.prototype._regenerateVertexData = function () {
  39019. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39020. };
  39021. BoxGeometry.prototype.copy = function (id) {
  39022. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39023. };
  39024. BoxGeometry.prototype.serialize = function () {
  39025. var serializationObject = _super.prototype.serialize.call(this);
  39026. serializationObject.size = this.size;
  39027. return serializationObject;
  39028. };
  39029. BoxGeometry.Parse = function (parsedBox, scene) {
  39030. if (scene.getGeometryByID(parsedBox.id)) {
  39031. return null; // null since geometry could be something else than a box...
  39032. }
  39033. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39034. if (BABYLON.Tags) {
  39035. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39036. }
  39037. scene.pushGeometry(box, true);
  39038. return box;
  39039. };
  39040. return BoxGeometry;
  39041. }(_PrimitiveGeometry));
  39042. BABYLON.BoxGeometry = BoxGeometry;
  39043. /**
  39044. * Creates a sphere geometry
  39045. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39046. */
  39047. var SphereGeometry = /** @class */ (function (_super) {
  39048. __extends(SphereGeometry, _super);
  39049. /**
  39050. * Create a new sphere geometry
  39051. * @param id defines the unique ID of the geometry
  39052. * @param scene defines the hosting scene
  39053. * @param segments defines the number of segments to use to create the sphere
  39054. * @param diameter defines the diameter of the sphere
  39055. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39056. * @param mesh defines the hosting mesh (can be null)
  39057. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39058. */
  39059. function SphereGeometry(id, scene,
  39060. /**
  39061. * Defines the number of segments to use to create the sphere
  39062. */
  39063. segments,
  39064. /**
  39065. * Defines the diameter of the sphere
  39066. */
  39067. diameter, canBeRegenerated, mesh,
  39068. /**
  39069. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39070. */
  39071. side) {
  39072. if (mesh === void 0) { mesh = null; }
  39073. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39074. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39075. _this.segments = segments;
  39076. _this.diameter = diameter;
  39077. _this.side = side;
  39078. return _this;
  39079. }
  39080. SphereGeometry.prototype._regenerateVertexData = function () {
  39081. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39082. };
  39083. SphereGeometry.prototype.copy = function (id) {
  39084. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39085. };
  39086. SphereGeometry.prototype.serialize = function () {
  39087. var serializationObject = _super.prototype.serialize.call(this);
  39088. serializationObject.segments = this.segments;
  39089. serializationObject.diameter = this.diameter;
  39090. return serializationObject;
  39091. };
  39092. SphereGeometry.Parse = function (parsedSphere, scene) {
  39093. if (scene.getGeometryByID(parsedSphere.id)) {
  39094. return null; // null since geometry could be something else than a sphere...
  39095. }
  39096. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39097. if (BABYLON.Tags) {
  39098. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39099. }
  39100. scene.pushGeometry(sphere, true);
  39101. return sphere;
  39102. };
  39103. return SphereGeometry;
  39104. }(_PrimitiveGeometry));
  39105. BABYLON.SphereGeometry = SphereGeometry;
  39106. /**
  39107. * Creates a disc geometry
  39108. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39109. */
  39110. var DiscGeometry = /** @class */ (function (_super) {
  39111. __extends(DiscGeometry, _super);
  39112. /**
  39113. * Creates a new disc geometry
  39114. * @param id defines the unique ID of the geometry
  39115. * @param scene defines the hosting scene
  39116. * @param radius defines the radius of the disc
  39117. * @param tessellation defines the tesselation factor to apply to the disc
  39118. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39119. * @param mesh defines the hosting mesh (can be null)
  39120. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39121. */
  39122. function DiscGeometry(id, scene,
  39123. /**
  39124. * Defines the radius of the disc
  39125. */
  39126. radius,
  39127. /**
  39128. * Defines the tesselation factor to apply to the disc
  39129. */
  39130. tessellation, canBeRegenerated, mesh,
  39131. /**
  39132. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39133. */
  39134. side) {
  39135. if (mesh === void 0) { mesh = null; }
  39136. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39137. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39138. _this.radius = radius;
  39139. _this.tessellation = tessellation;
  39140. _this.side = side;
  39141. return _this;
  39142. }
  39143. DiscGeometry.prototype._regenerateVertexData = function () {
  39144. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39145. };
  39146. DiscGeometry.prototype.copy = function (id) {
  39147. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39148. };
  39149. return DiscGeometry;
  39150. }(_PrimitiveGeometry));
  39151. BABYLON.DiscGeometry = DiscGeometry;
  39152. /**
  39153. * Creates a new cylinder geometry
  39154. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39155. */
  39156. var CylinderGeometry = /** @class */ (function (_super) {
  39157. __extends(CylinderGeometry, _super);
  39158. /**
  39159. * Creates a new cylinder geometry
  39160. * @param id defines the unique ID of the geometry
  39161. * @param scene defines the hosting scene
  39162. * @param height defines the height of the cylinder
  39163. * @param diameterTop defines the diameter of the cylinder's top cap
  39164. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39165. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39166. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39167. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39168. * @param mesh defines the hosting mesh (can be null)
  39169. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39170. */
  39171. function CylinderGeometry(id, scene,
  39172. /**
  39173. * Defines the height of the cylinder
  39174. */
  39175. height,
  39176. /**
  39177. * Defines the diameter of the cylinder's top cap
  39178. */
  39179. diameterTop,
  39180. /**
  39181. * Defines the diameter of the cylinder's bottom cap
  39182. */
  39183. diameterBottom,
  39184. /**
  39185. * Defines the tessellation factor to apply to the cylinder
  39186. */
  39187. tessellation,
  39188. /**
  39189. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39190. */
  39191. subdivisions, canBeRegenerated, mesh,
  39192. /**
  39193. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39194. */
  39195. side) {
  39196. if (subdivisions === void 0) { subdivisions = 1; }
  39197. if (mesh === void 0) { mesh = null; }
  39198. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39199. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39200. _this.height = height;
  39201. _this.diameterTop = diameterTop;
  39202. _this.diameterBottom = diameterBottom;
  39203. _this.tessellation = tessellation;
  39204. _this.subdivisions = subdivisions;
  39205. _this.side = side;
  39206. return _this;
  39207. }
  39208. CylinderGeometry.prototype._regenerateVertexData = function () {
  39209. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39210. };
  39211. CylinderGeometry.prototype.copy = function (id) {
  39212. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39213. };
  39214. CylinderGeometry.prototype.serialize = function () {
  39215. var serializationObject = _super.prototype.serialize.call(this);
  39216. serializationObject.height = this.height;
  39217. serializationObject.diameterTop = this.diameterTop;
  39218. serializationObject.diameterBottom = this.diameterBottom;
  39219. serializationObject.tessellation = this.tessellation;
  39220. return serializationObject;
  39221. };
  39222. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39223. if (scene.getGeometryByID(parsedCylinder.id)) {
  39224. return null; // null since geometry could be something else than a cylinder...
  39225. }
  39226. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39227. if (BABYLON.Tags) {
  39228. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39229. }
  39230. scene.pushGeometry(cylinder, true);
  39231. return cylinder;
  39232. };
  39233. return CylinderGeometry;
  39234. }(_PrimitiveGeometry));
  39235. BABYLON.CylinderGeometry = CylinderGeometry;
  39236. /**
  39237. * Creates a new torus geometry
  39238. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39239. */
  39240. var TorusGeometry = /** @class */ (function (_super) {
  39241. __extends(TorusGeometry, _super);
  39242. /**
  39243. * Creates a new torus geometry
  39244. * @param id defines the unique ID of the geometry
  39245. * @param scene defines the hosting scene
  39246. * @param diameter defines the diameter of the torus
  39247. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39248. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39249. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39250. * @param mesh defines the hosting mesh (can be null)
  39251. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39252. */
  39253. function TorusGeometry(id, scene,
  39254. /**
  39255. * Defines the diameter of the torus
  39256. */
  39257. diameter,
  39258. /**
  39259. * Defines the thickness of the torus (ie. internal diameter)
  39260. */
  39261. thickness,
  39262. /**
  39263. * Defines the tesselation factor to apply to the torus
  39264. */
  39265. tessellation, canBeRegenerated, mesh,
  39266. /**
  39267. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39268. */
  39269. side) {
  39270. if (mesh === void 0) { mesh = null; }
  39271. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39272. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39273. _this.diameter = diameter;
  39274. _this.thickness = thickness;
  39275. _this.tessellation = tessellation;
  39276. _this.side = side;
  39277. return _this;
  39278. }
  39279. TorusGeometry.prototype._regenerateVertexData = function () {
  39280. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39281. };
  39282. TorusGeometry.prototype.copy = function (id) {
  39283. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39284. };
  39285. TorusGeometry.prototype.serialize = function () {
  39286. var serializationObject = _super.prototype.serialize.call(this);
  39287. serializationObject.diameter = this.diameter;
  39288. serializationObject.thickness = this.thickness;
  39289. serializationObject.tessellation = this.tessellation;
  39290. return serializationObject;
  39291. };
  39292. TorusGeometry.Parse = function (parsedTorus, scene) {
  39293. if (scene.getGeometryByID(parsedTorus.id)) {
  39294. return null; // null since geometry could be something else than a torus...
  39295. }
  39296. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39297. if (BABYLON.Tags) {
  39298. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39299. }
  39300. scene.pushGeometry(torus, true);
  39301. return torus;
  39302. };
  39303. return TorusGeometry;
  39304. }(_PrimitiveGeometry));
  39305. BABYLON.TorusGeometry = TorusGeometry;
  39306. /**
  39307. * Creates a new ground geometry
  39308. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39309. */
  39310. var GroundGeometry = /** @class */ (function (_super) {
  39311. __extends(GroundGeometry, _super);
  39312. /**
  39313. * Creates a new ground geometry
  39314. * @param id defines the unique ID of the geometry
  39315. * @param scene defines the hosting scene
  39316. * @param width defines the width of the ground
  39317. * @param height defines the height of the ground
  39318. * @param subdivisions defines the subdivisions to apply to the ground
  39319. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39320. * @param mesh defines the hosting mesh (can be null)
  39321. */
  39322. function GroundGeometry(id, scene,
  39323. /**
  39324. * Defines the width of the ground
  39325. */
  39326. width,
  39327. /**
  39328. * Defines the height of the ground
  39329. */
  39330. height,
  39331. /**
  39332. * Defines the subdivisions to apply to the ground
  39333. */
  39334. subdivisions, canBeRegenerated, mesh) {
  39335. if (mesh === void 0) { mesh = null; }
  39336. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39337. _this.width = width;
  39338. _this.height = height;
  39339. _this.subdivisions = subdivisions;
  39340. return _this;
  39341. }
  39342. GroundGeometry.prototype._regenerateVertexData = function () {
  39343. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39344. };
  39345. GroundGeometry.prototype.copy = function (id) {
  39346. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39347. };
  39348. GroundGeometry.prototype.serialize = function () {
  39349. var serializationObject = _super.prototype.serialize.call(this);
  39350. serializationObject.width = this.width;
  39351. serializationObject.height = this.height;
  39352. serializationObject.subdivisions = this.subdivisions;
  39353. return serializationObject;
  39354. };
  39355. GroundGeometry.Parse = function (parsedGround, scene) {
  39356. if (scene.getGeometryByID(parsedGround.id)) {
  39357. return null; // null since geometry could be something else than a ground...
  39358. }
  39359. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39360. if (BABYLON.Tags) {
  39361. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39362. }
  39363. scene.pushGeometry(ground, true);
  39364. return ground;
  39365. };
  39366. return GroundGeometry;
  39367. }(_PrimitiveGeometry));
  39368. BABYLON.GroundGeometry = GroundGeometry;
  39369. /**
  39370. * Creates a tiled ground geometry
  39371. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39372. */
  39373. var TiledGroundGeometry = /** @class */ (function (_super) {
  39374. __extends(TiledGroundGeometry, _super);
  39375. /**
  39376. * Creates a tiled ground geometry
  39377. * @param id defines the unique ID of the geometry
  39378. * @param scene defines the hosting scene
  39379. * @param xmin defines the minimum value on X axis
  39380. * @param zmin defines the minimum value on Z axis
  39381. * @param xmax defines the maximum value on X axis
  39382. * @param zmax defines the maximum value on Z axis
  39383. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39384. * @param precision defines the precision to use when computing the tiles
  39385. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39386. * @param mesh defines the hosting mesh (can be null)
  39387. */
  39388. function TiledGroundGeometry(id, scene,
  39389. /**
  39390. * Defines the minimum value on X axis
  39391. */
  39392. xmin,
  39393. /**
  39394. * Defines the minimum value on Z axis
  39395. */
  39396. zmin,
  39397. /**
  39398. * Defines the maximum value on X axis
  39399. */
  39400. xmax,
  39401. /**
  39402. * Defines the maximum value on Z axis
  39403. */
  39404. zmax,
  39405. /**
  39406. * Defines the subdivisions to apply to the ground
  39407. */
  39408. subdivisions,
  39409. /**
  39410. * Defines the precision to use when computing the tiles
  39411. */
  39412. precision, canBeRegenerated, mesh) {
  39413. if (mesh === void 0) { mesh = null; }
  39414. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39415. _this.xmin = xmin;
  39416. _this.zmin = zmin;
  39417. _this.xmax = xmax;
  39418. _this.zmax = zmax;
  39419. _this.subdivisions = subdivisions;
  39420. _this.precision = precision;
  39421. return _this;
  39422. }
  39423. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39424. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39425. };
  39426. TiledGroundGeometry.prototype.copy = function (id) {
  39427. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39428. };
  39429. return TiledGroundGeometry;
  39430. }(_PrimitiveGeometry));
  39431. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39432. /**
  39433. * Creates a plane geometry
  39434. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39435. */
  39436. var PlaneGeometry = /** @class */ (function (_super) {
  39437. __extends(PlaneGeometry, _super);
  39438. /**
  39439. * Creates a plane geometry
  39440. * @param id defines the unique ID of the geometry
  39441. * @param scene defines the hosting scene
  39442. * @param size defines the size of the plane (width === height)
  39443. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39444. * @param mesh defines the hosting mesh (can be null)
  39445. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39446. */
  39447. function PlaneGeometry(id, scene,
  39448. /**
  39449. * Defines the size of the plane (width === height)
  39450. */
  39451. size, canBeRegenerated, mesh,
  39452. /**
  39453. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39454. */
  39455. side) {
  39456. if (mesh === void 0) { mesh = null; }
  39457. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39458. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39459. _this.size = size;
  39460. _this.side = side;
  39461. return _this;
  39462. }
  39463. PlaneGeometry.prototype._regenerateVertexData = function () {
  39464. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39465. };
  39466. PlaneGeometry.prototype.copy = function (id) {
  39467. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39468. };
  39469. PlaneGeometry.prototype.serialize = function () {
  39470. var serializationObject = _super.prototype.serialize.call(this);
  39471. serializationObject.size = this.size;
  39472. return serializationObject;
  39473. };
  39474. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39475. if (scene.getGeometryByID(parsedPlane.id)) {
  39476. return null; // null since geometry could be something else than a ground...
  39477. }
  39478. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39479. if (BABYLON.Tags) {
  39480. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  39481. }
  39482. scene.pushGeometry(plane, true);
  39483. return plane;
  39484. };
  39485. return PlaneGeometry;
  39486. }(_PrimitiveGeometry));
  39487. BABYLON.PlaneGeometry = PlaneGeometry;
  39488. /**
  39489. * Creates a torus knot geometry
  39490. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  39491. */
  39492. var TorusKnotGeometry = /** @class */ (function (_super) {
  39493. __extends(TorusKnotGeometry, _super);
  39494. /**
  39495. * Creates a torus knot geometry
  39496. * @param id defines the unique ID of the geometry
  39497. * @param scene defines the hosting scene
  39498. * @param radius defines the radius of the torus knot
  39499. * @param tube defines the thickness of the torus knot tube
  39500. * @param radialSegments defines the number of radial segments
  39501. * @param tubularSegments defines the number of tubular segments
  39502. * @param p defines the first number of windings
  39503. * @param q defines the second number of windings
  39504. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39505. * @param mesh defines the hosting mesh (can be null)
  39506. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39507. */
  39508. function TorusKnotGeometry(id, scene,
  39509. /**
  39510. * Defines the radius of the torus knot
  39511. */
  39512. radius,
  39513. /**
  39514. * Defines the thickness of the torus knot tube
  39515. */
  39516. tube,
  39517. /**
  39518. * Defines the number of radial segments
  39519. */
  39520. radialSegments,
  39521. /**
  39522. * Defines the number of tubular segments
  39523. */
  39524. tubularSegments,
  39525. /**
  39526. * Defines the first number of windings
  39527. */
  39528. p,
  39529. /**
  39530. * Defines the second number of windings
  39531. */
  39532. q, canBeRegenerated, mesh,
  39533. /**
  39534. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39535. */
  39536. side) {
  39537. if (mesh === void 0) { mesh = null; }
  39538. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39539. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39540. _this.radius = radius;
  39541. _this.tube = tube;
  39542. _this.radialSegments = radialSegments;
  39543. _this.tubularSegments = tubularSegments;
  39544. _this.p = p;
  39545. _this.q = q;
  39546. _this.side = side;
  39547. return _this;
  39548. }
  39549. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  39550. 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 });
  39551. };
  39552. TorusKnotGeometry.prototype.copy = function (id) {
  39553. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  39554. };
  39555. TorusKnotGeometry.prototype.serialize = function () {
  39556. var serializationObject = _super.prototype.serialize.call(this);
  39557. serializationObject.radius = this.radius;
  39558. serializationObject.tube = this.tube;
  39559. serializationObject.radialSegments = this.radialSegments;
  39560. serializationObject.tubularSegments = this.tubularSegments;
  39561. serializationObject.p = this.p;
  39562. serializationObject.q = this.q;
  39563. return serializationObject;
  39564. };
  39565. ;
  39566. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  39567. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  39568. return null; // null since geometry could be something else than a ground...
  39569. }
  39570. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  39571. if (BABYLON.Tags) {
  39572. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  39573. }
  39574. scene.pushGeometry(torusKnot, true);
  39575. return torusKnot;
  39576. };
  39577. return TorusKnotGeometry;
  39578. }(_PrimitiveGeometry));
  39579. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  39580. //}
  39581. })(BABYLON || (BABYLON = {}));
  39582. //# sourceMappingURL=babylon.geometry.js.map
  39583. "use strict";
  39584. var BABYLON;
  39585. (function (BABYLON) {
  39586. /**
  39587. * PostProcessManager is used to manage one or more post processes or post process pipelines
  39588. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  39589. */
  39590. var PostProcessManager = /** @class */ (function () {
  39591. /**
  39592. * Creates a new instance PostProcess
  39593. * @param scene The scene that the post process is associated with.
  39594. */
  39595. function PostProcessManager(scene) {
  39596. this._vertexBuffers = {};
  39597. this._scene = scene;
  39598. }
  39599. PostProcessManager.prototype._prepareBuffers = function () {
  39600. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  39601. return;
  39602. }
  39603. // VBO
  39604. var vertices = [];
  39605. vertices.push(1, 1);
  39606. vertices.push(-1, 1);
  39607. vertices.push(-1, -1);
  39608. vertices.push(1, -1);
  39609. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39610. this._buildIndexBuffer();
  39611. };
  39612. PostProcessManager.prototype._buildIndexBuffer = function () {
  39613. // Indices
  39614. var indices = [];
  39615. indices.push(0);
  39616. indices.push(1);
  39617. indices.push(2);
  39618. indices.push(0);
  39619. indices.push(2);
  39620. indices.push(3);
  39621. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  39622. };
  39623. /**
  39624. * Rebuilds the vertex buffers of the manager.
  39625. */
  39626. PostProcessManager.prototype._rebuild = function () {
  39627. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39628. if (!vb) {
  39629. return;
  39630. }
  39631. vb._rebuild();
  39632. this._buildIndexBuffer();
  39633. };
  39634. // Methods
  39635. /**
  39636. * Prepares a frame to be run through a post process.
  39637. * @param sourceTexture The input texture to the post procesess. (default: null)
  39638. * @param postProcesses An array of post processes to be run. (default: null)
  39639. * @returns True if the post processes were able to be run.
  39640. */
  39641. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  39642. if (sourceTexture === void 0) { sourceTexture = null; }
  39643. if (postProcesses === void 0) { postProcesses = null; }
  39644. var camera = this._scene.activeCamera;
  39645. if (!camera) {
  39646. return false;
  39647. }
  39648. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39649. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39650. return false;
  39651. }
  39652. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  39653. return true;
  39654. };
  39655. /**
  39656. * Manually render a set of post processes to a texture.
  39657. * @param postProcesses An array of post processes to be run.
  39658. * @param targetTexture The target texture to render to.
  39659. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  39660. */
  39661. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  39662. if (targetTexture === void 0) { targetTexture = null; }
  39663. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39664. var engine = this._scene.getEngine();
  39665. for (var index = 0; index < postProcesses.length; index++) {
  39666. if (index < postProcesses.length - 1) {
  39667. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  39668. }
  39669. else {
  39670. if (targetTexture) {
  39671. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  39672. }
  39673. else {
  39674. engine.restoreDefaultFramebuffer();
  39675. }
  39676. }
  39677. var pp = postProcesses[index];
  39678. var effect = pp.apply();
  39679. if (effect) {
  39680. pp.onBeforeRenderObservable.notifyObservers(effect);
  39681. // VBOs
  39682. this._prepareBuffers();
  39683. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39684. // Draw order
  39685. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39686. pp.onAfterRenderObservable.notifyObservers(effect);
  39687. }
  39688. }
  39689. // Restore depth buffer
  39690. engine.setDepthBuffer(true);
  39691. engine.setDepthWrite(true);
  39692. };
  39693. /**
  39694. * Finalize the result of the output of the postprocesses.
  39695. * @param doNotPresent If true the result will not be displayed to the screen.
  39696. * @param targetTexture The target texture to render to.
  39697. * @param faceIndex The index of the face to bind the target texture to.
  39698. * @param postProcesses The array of post processes to render.
  39699. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  39700. */
  39701. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  39702. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39703. var camera = this._scene.activeCamera;
  39704. if (!camera) {
  39705. return;
  39706. }
  39707. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39708. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39709. return;
  39710. }
  39711. var engine = this._scene.getEngine();
  39712. for (var index = 0, len = postProcesses.length; index < len; index++) {
  39713. var pp = postProcesses[index];
  39714. if (index < len - 1) {
  39715. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  39716. }
  39717. else {
  39718. if (targetTexture) {
  39719. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  39720. pp._outputTexture = targetTexture;
  39721. }
  39722. else {
  39723. engine.restoreDefaultFramebuffer();
  39724. pp._outputTexture = null;
  39725. }
  39726. }
  39727. if (doNotPresent) {
  39728. break;
  39729. }
  39730. var effect = pp.apply();
  39731. if (effect) {
  39732. pp.onBeforeRenderObservable.notifyObservers(effect);
  39733. // VBOs
  39734. this._prepareBuffers();
  39735. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39736. // Draw order
  39737. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39738. pp.onAfterRenderObservable.notifyObservers(effect);
  39739. }
  39740. }
  39741. // Restore states
  39742. engine.setDepthBuffer(true);
  39743. engine.setDepthWrite(true);
  39744. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39745. };
  39746. /**
  39747. * Disposes of the post process manager.
  39748. */
  39749. PostProcessManager.prototype.dispose = function () {
  39750. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39751. if (buffer) {
  39752. buffer.dispose();
  39753. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39754. }
  39755. if (this._indexBuffer) {
  39756. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39757. this._indexBuffer = null;
  39758. }
  39759. };
  39760. return PostProcessManager;
  39761. }());
  39762. BABYLON.PostProcessManager = PostProcessManager;
  39763. })(BABYLON || (BABYLON = {}));
  39764. //# sourceMappingURL=babylon.postProcessManager.js.map
  39765. "use strict";
  39766. var BABYLON;
  39767. (function (BABYLON) {
  39768. /**
  39769. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  39770. */
  39771. var PerformanceMonitor = /** @class */ (function () {
  39772. /**
  39773. * constructor
  39774. * @param frameSampleSize The number of samples required to saturate the sliding window
  39775. */
  39776. function PerformanceMonitor(frameSampleSize) {
  39777. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  39778. this._enabled = true;
  39779. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  39780. }
  39781. /**
  39782. * Samples current frame
  39783. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  39784. */
  39785. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  39786. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  39787. if (!this._enabled)
  39788. return;
  39789. if (this._lastFrameTimeMs != null) {
  39790. var dt = timeMs - this._lastFrameTimeMs;
  39791. this._rollingFrameTime.add(dt);
  39792. }
  39793. this._lastFrameTimeMs = timeMs;
  39794. };
  39795. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  39796. /**
  39797. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  39798. * @return Average frame time in milliseconds
  39799. */
  39800. get: function () {
  39801. return this._rollingFrameTime.average;
  39802. },
  39803. enumerable: true,
  39804. configurable: true
  39805. });
  39806. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  39807. /**
  39808. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  39809. * @return Frame time variance in milliseconds squared
  39810. */
  39811. get: function () {
  39812. return this._rollingFrameTime.variance;
  39813. },
  39814. enumerable: true,
  39815. configurable: true
  39816. });
  39817. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  39818. /**
  39819. * Returns the frame time of the most recent frame
  39820. * @return Frame time in milliseconds
  39821. */
  39822. get: function () {
  39823. return this._rollingFrameTime.history(0);
  39824. },
  39825. enumerable: true,
  39826. configurable: true
  39827. });
  39828. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  39829. /**
  39830. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  39831. * @return Framerate in frames per second
  39832. */
  39833. get: function () {
  39834. return 1000.0 / this._rollingFrameTime.average;
  39835. },
  39836. enumerable: true,
  39837. configurable: true
  39838. });
  39839. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  39840. /**
  39841. * Returns the average framerate in frames per second using the most recent frame time
  39842. * @return Framerate in frames per second
  39843. */
  39844. get: function () {
  39845. var history = this._rollingFrameTime.history(0);
  39846. if (history === 0) {
  39847. return 0;
  39848. }
  39849. return 1000.0 / history;
  39850. },
  39851. enumerable: true,
  39852. configurable: true
  39853. });
  39854. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  39855. /**
  39856. * Returns true if enough samples have been taken to completely fill the sliding window
  39857. * @return true if saturated
  39858. */
  39859. get: function () {
  39860. return this._rollingFrameTime.isSaturated();
  39861. },
  39862. enumerable: true,
  39863. configurable: true
  39864. });
  39865. /**
  39866. * Enables contributions to the sliding window sample set
  39867. */
  39868. PerformanceMonitor.prototype.enable = function () {
  39869. this._enabled = true;
  39870. };
  39871. /**
  39872. * Disables contributions to the sliding window sample set
  39873. * Samples will not be interpolated over the disabled period
  39874. */
  39875. PerformanceMonitor.prototype.disable = function () {
  39876. this._enabled = false;
  39877. //clear last sample to avoid interpolating over the disabled period when next enabled
  39878. this._lastFrameTimeMs = null;
  39879. };
  39880. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  39881. /**
  39882. * Returns true if sampling is enabled
  39883. * @return true if enabled
  39884. */
  39885. get: function () {
  39886. return this._enabled;
  39887. },
  39888. enumerable: true,
  39889. configurable: true
  39890. });
  39891. /**
  39892. * Resets performance monitor
  39893. */
  39894. PerformanceMonitor.prototype.reset = function () {
  39895. //clear last sample to avoid interpolating over the disabled period when next enabled
  39896. this._lastFrameTimeMs = null;
  39897. //wipe record
  39898. this._rollingFrameTime.reset();
  39899. };
  39900. return PerformanceMonitor;
  39901. }());
  39902. BABYLON.PerformanceMonitor = PerformanceMonitor;
  39903. /**
  39904. * RollingAverage
  39905. *
  39906. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  39907. */
  39908. var RollingAverage = /** @class */ (function () {
  39909. /**
  39910. * constructor
  39911. * @param length The number of samples required to saturate the sliding window
  39912. */
  39913. function RollingAverage(length) {
  39914. this._samples = new Array(length);
  39915. this.reset();
  39916. }
  39917. /**
  39918. * Adds a sample to the sample set
  39919. * @param v The sample value
  39920. */
  39921. RollingAverage.prototype.add = function (v) {
  39922. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  39923. var delta;
  39924. //we need to check if we've already wrapped round
  39925. if (this.isSaturated()) {
  39926. //remove bottom of stack from mean
  39927. var bottomValue = this._samples[this._pos];
  39928. delta = bottomValue - this.average;
  39929. this.average -= delta / (this._sampleCount - 1);
  39930. this._m2 -= delta * (bottomValue - this.average);
  39931. }
  39932. else {
  39933. this._sampleCount++;
  39934. }
  39935. //add new value to mean
  39936. delta = v - this.average;
  39937. this.average += delta / (this._sampleCount);
  39938. this._m2 += delta * (v - this.average);
  39939. //set the new variance
  39940. this.variance = this._m2 / (this._sampleCount - 1);
  39941. this._samples[this._pos] = v;
  39942. this._pos++;
  39943. this._pos %= this._samples.length; //positive wrap around
  39944. };
  39945. /**
  39946. * Returns previously added values or null if outside of history or outside the sliding window domain
  39947. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  39948. * @return Value previously recorded with add() or null if outside of range
  39949. */
  39950. RollingAverage.prototype.history = function (i) {
  39951. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  39952. return 0;
  39953. }
  39954. var i0 = this._wrapPosition(this._pos - 1.0);
  39955. return this._samples[this._wrapPosition(i0 - i)];
  39956. };
  39957. /**
  39958. * Returns true if enough samples have been taken to completely fill the sliding window
  39959. * @return true if sample-set saturated
  39960. */
  39961. RollingAverage.prototype.isSaturated = function () {
  39962. return this._sampleCount >= this._samples.length;
  39963. };
  39964. /**
  39965. * Resets the rolling average (equivalent to 0 samples taken so far)
  39966. */
  39967. RollingAverage.prototype.reset = function () {
  39968. this.average = 0;
  39969. this.variance = 0;
  39970. this._sampleCount = 0;
  39971. this._pos = 0;
  39972. this._m2 = 0;
  39973. };
  39974. /**
  39975. * Wraps a value around the sample range boundaries
  39976. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  39977. * @return Wrapped position in sample range
  39978. */
  39979. RollingAverage.prototype._wrapPosition = function (i) {
  39980. var max = this._samples.length;
  39981. return ((i % max) + max) % max;
  39982. };
  39983. return RollingAverage;
  39984. }());
  39985. BABYLON.RollingAverage = RollingAverage;
  39986. })(BABYLON || (BABYLON = {}));
  39987. //# sourceMappingURL=babylon.performanceMonitor.js.map
  39988. "use strict";
  39989. var BABYLON;
  39990. (function (BABYLON) {
  39991. /**
  39992. * This groups together the common properties used for image processing either in direct forward pass
  39993. * or through post processing effect depending on the use of the image processing pipeline in your scene
  39994. * or not.
  39995. */
  39996. var ImageProcessingConfiguration = /** @class */ (function () {
  39997. function ImageProcessingConfiguration() {
  39998. /**
  39999. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40000. */
  40001. this.colorCurves = new BABYLON.ColorCurves();
  40002. this._colorCurvesEnabled = false;
  40003. this._colorGradingEnabled = false;
  40004. this._colorGradingWithGreenDepth = true;
  40005. this._colorGradingBGR = true;
  40006. this._exposure = 1.0;
  40007. this._toneMappingEnabled = false;
  40008. this._contrast = 1.0;
  40009. /**
  40010. * Vignette stretch size.
  40011. */
  40012. this.vignetteStretch = 0;
  40013. /**
  40014. * Vignette centre X Offset.
  40015. */
  40016. this.vignetteCentreX = 0;
  40017. /**
  40018. * Vignette centre Y Offset.
  40019. */
  40020. this.vignetteCentreY = 0;
  40021. /**
  40022. * Vignette weight or intensity of the vignette effect.
  40023. */
  40024. this.vignetteWeight = 1.5;
  40025. /**
  40026. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40027. * if vignetteEnabled is set to true.
  40028. */
  40029. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40030. /**
  40031. * Camera field of view used by the Vignette effect.
  40032. */
  40033. this.vignetteCameraFov = 0.5;
  40034. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40035. this._vignetteEnabled = false;
  40036. this._applyByPostProcess = false;
  40037. this._isEnabled = true;
  40038. /**
  40039. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40040. */
  40041. this.onUpdateParameters = new BABYLON.Observable();
  40042. }
  40043. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40044. /**
  40045. * Gets wether the color curves effect is enabled.
  40046. */
  40047. get: function () {
  40048. return this._colorCurvesEnabled;
  40049. },
  40050. /**
  40051. * Sets wether the color curves effect is enabled.
  40052. */
  40053. set: function (value) {
  40054. if (this._colorCurvesEnabled === value) {
  40055. return;
  40056. }
  40057. this._colorCurvesEnabled = value;
  40058. this._updateParameters();
  40059. },
  40060. enumerable: true,
  40061. configurable: true
  40062. });
  40063. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40064. /**
  40065. * Gets wether the color grading effect is enabled.
  40066. */
  40067. get: function () {
  40068. return this._colorGradingEnabled;
  40069. },
  40070. /**
  40071. * Sets wether the color grading effect is enabled.
  40072. */
  40073. set: function (value) {
  40074. if (this._colorGradingEnabled === value) {
  40075. return;
  40076. }
  40077. this._colorGradingEnabled = value;
  40078. this._updateParameters();
  40079. },
  40080. enumerable: true,
  40081. configurable: true
  40082. });
  40083. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40084. /**
  40085. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40086. */
  40087. get: function () {
  40088. return this._colorGradingWithGreenDepth;
  40089. },
  40090. /**
  40091. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40092. */
  40093. set: function (value) {
  40094. if (this._colorGradingWithGreenDepth === value) {
  40095. return;
  40096. }
  40097. this._colorGradingWithGreenDepth = value;
  40098. this._updateParameters();
  40099. },
  40100. enumerable: true,
  40101. configurable: true
  40102. });
  40103. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40104. /**
  40105. * Gets wether the color grading texture contains BGR values.
  40106. */
  40107. get: function () {
  40108. return this._colorGradingBGR;
  40109. },
  40110. /**
  40111. * Sets wether the color grading texture contains BGR values.
  40112. */
  40113. set: function (value) {
  40114. if (this._colorGradingBGR === value) {
  40115. return;
  40116. }
  40117. this._colorGradingBGR = value;
  40118. this._updateParameters();
  40119. },
  40120. enumerable: true,
  40121. configurable: true
  40122. });
  40123. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40124. /**
  40125. * Gets the Exposure used in the effect.
  40126. */
  40127. get: function () {
  40128. return this._exposure;
  40129. },
  40130. /**
  40131. * Sets the Exposure used in the effect.
  40132. */
  40133. set: function (value) {
  40134. if (this._exposure === value) {
  40135. return;
  40136. }
  40137. this._exposure = value;
  40138. this._updateParameters();
  40139. },
  40140. enumerable: true,
  40141. configurable: true
  40142. });
  40143. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40144. /**
  40145. * Gets wether the tone mapping effect is enabled.
  40146. */
  40147. get: function () {
  40148. return this._toneMappingEnabled;
  40149. },
  40150. /**
  40151. * Sets wether the tone mapping effect is enabled.
  40152. */
  40153. set: function (value) {
  40154. if (this._toneMappingEnabled === value) {
  40155. return;
  40156. }
  40157. this._toneMappingEnabled = value;
  40158. this._updateParameters();
  40159. },
  40160. enumerable: true,
  40161. configurable: true
  40162. });
  40163. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40164. /**
  40165. * Gets the contrast used in the effect.
  40166. */
  40167. get: function () {
  40168. return this._contrast;
  40169. },
  40170. /**
  40171. * Sets the contrast used in the effect.
  40172. */
  40173. set: function (value) {
  40174. if (this._contrast === value) {
  40175. return;
  40176. }
  40177. this._contrast = value;
  40178. this._updateParameters();
  40179. },
  40180. enumerable: true,
  40181. configurable: true
  40182. });
  40183. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40184. /**
  40185. * Gets the vignette blend mode allowing different kind of effect.
  40186. */
  40187. get: function () {
  40188. return this._vignetteBlendMode;
  40189. },
  40190. /**
  40191. * Sets the vignette blend mode allowing different kind of effect.
  40192. */
  40193. set: function (value) {
  40194. if (this._vignetteBlendMode === value) {
  40195. return;
  40196. }
  40197. this._vignetteBlendMode = value;
  40198. this._updateParameters();
  40199. },
  40200. enumerable: true,
  40201. configurable: true
  40202. });
  40203. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40204. /**
  40205. * Gets wether the vignette effect is enabled.
  40206. */
  40207. get: function () {
  40208. return this._vignetteEnabled;
  40209. },
  40210. /**
  40211. * Sets wether the vignette effect is enabled.
  40212. */
  40213. set: function (value) {
  40214. if (this._vignetteEnabled === value) {
  40215. return;
  40216. }
  40217. this._vignetteEnabled = value;
  40218. this._updateParameters();
  40219. },
  40220. enumerable: true,
  40221. configurable: true
  40222. });
  40223. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40224. /**
  40225. * Gets wether the image processing is applied through a post process or not.
  40226. */
  40227. get: function () {
  40228. return this._applyByPostProcess;
  40229. },
  40230. /**
  40231. * Sets wether the image processing is applied through a post process or not.
  40232. */
  40233. set: function (value) {
  40234. if (this._applyByPostProcess === value) {
  40235. return;
  40236. }
  40237. this._applyByPostProcess = value;
  40238. this._updateParameters();
  40239. },
  40240. enumerable: true,
  40241. configurable: true
  40242. });
  40243. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40244. /**
  40245. * Gets wether the image processing is enabled or not.
  40246. */
  40247. get: function () {
  40248. return this._isEnabled;
  40249. },
  40250. /**
  40251. * Sets wether the image processing is enabled or not.
  40252. */
  40253. set: function (value) {
  40254. if (this._isEnabled === value) {
  40255. return;
  40256. }
  40257. this._isEnabled = value;
  40258. this._updateParameters();
  40259. },
  40260. enumerable: true,
  40261. configurable: true
  40262. });
  40263. /**
  40264. * Method called each time the image processing information changes requires to recompile the effect.
  40265. */
  40266. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40267. this.onUpdateParameters.notifyObservers(this);
  40268. };
  40269. ImageProcessingConfiguration.prototype.getClassName = function () {
  40270. return "ImageProcessingConfiguration";
  40271. };
  40272. /**
  40273. * Prepare the list of uniforms associated with the Image Processing effects.
  40274. * @param uniformsList The list of uniforms used in the effect
  40275. * @param defines the list of defines currently in use
  40276. */
  40277. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40278. if (defines.EXPOSURE) {
  40279. uniforms.push("exposureLinear");
  40280. }
  40281. if (defines.CONTRAST) {
  40282. uniforms.push("contrast");
  40283. }
  40284. if (defines.COLORGRADING) {
  40285. uniforms.push("colorTransformSettings");
  40286. }
  40287. if (defines.VIGNETTE) {
  40288. uniforms.push("vInverseScreenSize");
  40289. uniforms.push("vignetteSettings1");
  40290. uniforms.push("vignetteSettings2");
  40291. }
  40292. if (defines.COLORCURVES) {
  40293. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40294. }
  40295. };
  40296. /**
  40297. * Prepare the list of samplers associated with the Image Processing effects.
  40298. * @param uniformsList The list of uniforms used in the effect
  40299. * @param defines the list of defines currently in use
  40300. */
  40301. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40302. if (defines.COLORGRADING) {
  40303. samplersList.push("txColorTransform");
  40304. }
  40305. };
  40306. /**
  40307. * Prepare the list of defines associated to the shader.
  40308. * @param defines the list of defines to complete
  40309. */
  40310. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  40311. if (forPostProcess === void 0) { forPostProcess = false; }
  40312. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  40313. defines.VIGNETTE = false;
  40314. defines.TONEMAPPING = false;
  40315. defines.CONTRAST = false;
  40316. defines.EXPOSURE = false;
  40317. defines.COLORCURVES = false;
  40318. defines.COLORGRADING = false;
  40319. defines.COLORGRADING3D = false;
  40320. defines.IMAGEPROCESSING = false;
  40321. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  40322. return;
  40323. }
  40324. defines.VIGNETTE = this.vignetteEnabled;
  40325. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40326. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40327. defines.TONEMAPPING = this.toneMappingEnabled;
  40328. defines.CONTRAST = (this.contrast !== 1.0);
  40329. defines.EXPOSURE = (this.exposure !== 1.0);
  40330. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40331. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40332. if (defines.COLORGRADING) {
  40333. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  40334. }
  40335. else {
  40336. defines.COLORGRADING3D = false;
  40337. }
  40338. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40339. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40340. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40341. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40342. };
  40343. /**
  40344. * Returns true if all the image processing information are ready.
  40345. */
  40346. ImageProcessingConfiguration.prototype.isReady = function () {
  40347. // Color Grading texure can not be none blocking.
  40348. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40349. };
  40350. /**
  40351. * Binds the image processing to the shader.
  40352. * @param effect The effect to bind to
  40353. */
  40354. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40355. if (aspectRatio === void 0) { aspectRatio = 1; }
  40356. // Color Curves
  40357. if (this._colorCurvesEnabled && this.colorCurves) {
  40358. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40359. }
  40360. // Vignette
  40361. if (this._vignetteEnabled) {
  40362. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40363. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40364. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40365. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40366. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40367. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40368. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40369. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40370. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40371. var vignettePower = -2.0 * this.vignetteWeight;
  40372. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40373. }
  40374. // Exposure
  40375. effect.setFloat("exposureLinear", this.exposure);
  40376. // Contrast
  40377. effect.setFloat("contrast", this.contrast);
  40378. // Color transform settings
  40379. if (this.colorGradingTexture) {
  40380. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40381. var textureSize = this.colorGradingTexture.getSize().height;
  40382. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40383. 0.5 / textureSize, // textureOffset
  40384. textureSize, // textureSize
  40385. this.colorGradingTexture.level // weight
  40386. );
  40387. }
  40388. };
  40389. /**
  40390. * Clones the current image processing instance.
  40391. * @return The cloned image processing
  40392. */
  40393. ImageProcessingConfiguration.prototype.clone = function () {
  40394. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40395. };
  40396. /**
  40397. * Serializes the current image processing instance to a json representation.
  40398. * @return a JSON representation
  40399. */
  40400. ImageProcessingConfiguration.prototype.serialize = function () {
  40401. return BABYLON.SerializationHelper.Serialize(this);
  40402. };
  40403. /**
  40404. * Parses the image processing from a json representation.
  40405. * @param source the JSON source to parse
  40406. * @return The parsed image processing
  40407. */
  40408. ImageProcessingConfiguration.Parse = function (source) {
  40409. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40410. };
  40411. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40412. /**
  40413. * Used to apply the vignette as a mix with the pixel color.
  40414. */
  40415. get: function () {
  40416. return this._VIGNETTEMODE_MULTIPLY;
  40417. },
  40418. enumerable: true,
  40419. configurable: true
  40420. });
  40421. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40422. /**
  40423. * Used to apply the vignette as a replacement of the pixel color.
  40424. */
  40425. get: function () {
  40426. return this._VIGNETTEMODE_OPAQUE;
  40427. },
  40428. enumerable: true,
  40429. configurable: true
  40430. });
  40431. // Static constants associated to the image processing.
  40432. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40433. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40434. __decorate([
  40435. BABYLON.serializeAsColorCurves()
  40436. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40437. __decorate([
  40438. BABYLON.serialize()
  40439. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40440. __decorate([
  40441. BABYLON.serializeAsTexture()
  40442. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40443. __decorate([
  40444. BABYLON.serialize()
  40445. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40446. __decorate([
  40447. BABYLON.serialize()
  40448. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40449. __decorate([
  40450. BABYLON.serialize()
  40451. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40452. __decorate([
  40453. BABYLON.serialize()
  40454. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40455. __decorate([
  40456. BABYLON.serialize()
  40457. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40458. __decorate([
  40459. BABYLON.serialize()
  40460. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40461. __decorate([
  40462. BABYLON.serialize()
  40463. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40464. __decorate([
  40465. BABYLON.serialize()
  40466. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40467. __decorate([
  40468. BABYLON.serialize()
  40469. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40470. __decorate([
  40471. BABYLON.serialize()
  40472. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40473. __decorate([
  40474. BABYLON.serializeAsColor4()
  40475. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40476. __decorate([
  40477. BABYLON.serialize()
  40478. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40479. __decorate([
  40480. BABYLON.serialize()
  40481. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40482. __decorate([
  40483. BABYLON.serialize()
  40484. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40485. __decorate([
  40486. BABYLON.serialize()
  40487. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40488. __decorate([
  40489. BABYLON.serialize()
  40490. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  40491. return ImageProcessingConfiguration;
  40492. }());
  40493. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40494. })(BABYLON || (BABYLON = {}));
  40495. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40496. "use strict";
  40497. var BABYLON;
  40498. (function (BABYLON) {
  40499. /**
  40500. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40501. * It can help converting any input color in a desired output one. This can then be used to create effects
  40502. * from sepia, black and white to sixties or futuristic rendering...
  40503. *
  40504. * The only supported format is currently 3dl.
  40505. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40506. */
  40507. var ColorGradingTexture = /** @class */ (function (_super) {
  40508. __extends(ColorGradingTexture, _super);
  40509. /**
  40510. * Instantiates a ColorGradingTexture from the following parameters.
  40511. *
  40512. * @param url The location of the color gradind data (currently only supporting 3dl)
  40513. * @param scene The scene the texture will be used in
  40514. */
  40515. function ColorGradingTexture(url, scene) {
  40516. var _this = _super.call(this, scene) || this;
  40517. if (!url) {
  40518. return _this;
  40519. }
  40520. _this._engine = scene.getEngine();
  40521. _this._textureMatrix = BABYLON.Matrix.Identity();
  40522. _this.name = url;
  40523. _this.url = url;
  40524. _this.hasAlpha = false;
  40525. _this.isCube = false;
  40526. _this.is3D = _this._engine.webGLVersion > 1;
  40527. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40528. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40529. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40530. _this.anisotropicFilteringLevel = 1;
  40531. _this._texture = _this._getFromCache(url, true);
  40532. if (!_this._texture) {
  40533. if (!scene.useDelayedTextureLoading) {
  40534. _this.loadTexture();
  40535. }
  40536. else {
  40537. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40538. }
  40539. }
  40540. return _this;
  40541. }
  40542. /**
  40543. * Returns the texture matrix used in most of the material.
  40544. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  40545. */
  40546. ColorGradingTexture.prototype.getTextureMatrix = function () {
  40547. return this._textureMatrix;
  40548. };
  40549. /**
  40550. * Occurs when the file being loaded is a .3dl LUT file.
  40551. */
  40552. ColorGradingTexture.prototype.load3dlTexture = function () {
  40553. var engine = this._engine;
  40554. var texture;
  40555. if (engine.webGLVersion === 1) {
  40556. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40557. }
  40558. else {
  40559. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40560. }
  40561. this._texture = texture;
  40562. var callback = function (text) {
  40563. if (typeof text !== "string") {
  40564. return;
  40565. }
  40566. var data = null;
  40567. var tempData = null;
  40568. var line;
  40569. var lines = text.split('\n');
  40570. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  40571. var maxColor = 0;
  40572. for (var i = 0; i < lines.length; i++) {
  40573. line = lines[i];
  40574. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  40575. continue;
  40576. if (line.indexOf('#') === 0)
  40577. continue;
  40578. var words = line.split(" ");
  40579. if (size === 0) {
  40580. // Number of space + one
  40581. size = words.length;
  40582. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  40583. tempData = new Float32Array(size * size * size * 4);
  40584. continue;
  40585. }
  40586. if (size != 0) {
  40587. var r = Math.max(parseInt(words[0]), 0);
  40588. var g = Math.max(parseInt(words[1]), 0);
  40589. var b = Math.max(parseInt(words[2]), 0);
  40590. maxColor = Math.max(r, maxColor);
  40591. maxColor = Math.max(g, maxColor);
  40592. maxColor = Math.max(b, maxColor);
  40593. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  40594. if (tempData) {
  40595. tempData[pixelStorageIndex + 0] = r;
  40596. tempData[pixelStorageIndex + 1] = g;
  40597. tempData[pixelStorageIndex + 2] = b;
  40598. }
  40599. pixelIndexSlice++;
  40600. if (pixelIndexSlice % size == 0) {
  40601. pixelIndexH++;
  40602. pixelIndexSlice = 0;
  40603. if (pixelIndexH % size == 0) {
  40604. pixelIndexW++;
  40605. pixelIndexH = 0;
  40606. }
  40607. }
  40608. }
  40609. }
  40610. if (tempData && data) {
  40611. for (var i = 0; i < tempData.length; i++) {
  40612. if (i > 0 && (i + 1) % 4 === 0) {
  40613. data[i] = 255;
  40614. }
  40615. else {
  40616. var value = tempData[i];
  40617. data[i] = (value / maxColor * 255);
  40618. }
  40619. }
  40620. }
  40621. if (texture.is3D) {
  40622. texture.updateSize(size, size, size);
  40623. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40624. }
  40625. else {
  40626. texture.updateSize(size * size, size);
  40627. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40628. }
  40629. };
  40630. var scene = this.getScene();
  40631. if (scene) {
  40632. scene._loadFile(this.url, callback);
  40633. }
  40634. else {
  40635. this._engine._loadFile(this.url, callback);
  40636. }
  40637. return this._texture;
  40638. };
  40639. /**
  40640. * Starts the loading process of the texture.
  40641. */
  40642. ColorGradingTexture.prototype.loadTexture = function () {
  40643. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  40644. this.load3dlTexture();
  40645. }
  40646. };
  40647. /**
  40648. * Clones the color gradind texture.
  40649. */
  40650. ColorGradingTexture.prototype.clone = function () {
  40651. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  40652. // Base texture
  40653. newTexture.level = this.level;
  40654. return newTexture;
  40655. };
  40656. /**
  40657. * Called during delayed load for textures.
  40658. */
  40659. ColorGradingTexture.prototype.delayLoad = function () {
  40660. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40661. return;
  40662. }
  40663. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40664. this._texture = this._getFromCache(this.url, true);
  40665. if (!this._texture) {
  40666. this.loadTexture();
  40667. }
  40668. };
  40669. /**
  40670. * Parses a color grading texture serialized by Babylon.
  40671. * @param parsedTexture The texture information being parsedTexture
  40672. * @param scene The scene to load the texture in
  40673. * @param rootUrl The root url of the data assets to load
  40674. * @return A color gradind texture
  40675. */
  40676. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40677. var texture = null;
  40678. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40679. texture = new ColorGradingTexture(parsedTexture.name, scene);
  40680. texture.name = parsedTexture.name;
  40681. texture.level = parsedTexture.level;
  40682. }
  40683. return texture;
  40684. };
  40685. /**
  40686. * Serializes the LUT texture to json format.
  40687. */
  40688. ColorGradingTexture.prototype.serialize = function () {
  40689. if (!this.name) {
  40690. return null;
  40691. }
  40692. var serializationObject = {};
  40693. serializationObject.name = this.name;
  40694. serializationObject.level = this.level;
  40695. serializationObject.customType = "BABYLON.ColorGradingTexture";
  40696. return serializationObject;
  40697. };
  40698. /**
  40699. * Empty line regex stored for GC.
  40700. */
  40701. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  40702. return ColorGradingTexture;
  40703. }(BABYLON.BaseTexture));
  40704. BABYLON.ColorGradingTexture = ColorGradingTexture;
  40705. })(BABYLON || (BABYLON = {}));
  40706. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  40707. "use strict";
  40708. var BABYLON;
  40709. (function (BABYLON) {
  40710. /**
  40711. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40712. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40713. * 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;
  40714. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40715. */
  40716. var ColorCurves = /** @class */ (function () {
  40717. function ColorCurves() {
  40718. this._dirty = true;
  40719. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  40720. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  40721. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40722. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  40723. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40724. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  40725. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  40726. this._globalHue = 30;
  40727. this._globalDensity = 0;
  40728. this._globalSaturation = 0;
  40729. this._globalExposure = 0;
  40730. this._highlightsHue = 30;
  40731. this._highlightsDensity = 0;
  40732. this._highlightsSaturation = 0;
  40733. this._highlightsExposure = 0;
  40734. this._midtonesHue = 30;
  40735. this._midtonesDensity = 0;
  40736. this._midtonesSaturation = 0;
  40737. this._midtonesExposure = 0;
  40738. this._shadowsHue = 30;
  40739. this._shadowsDensity = 0;
  40740. this._shadowsSaturation = 0;
  40741. this._shadowsExposure = 0;
  40742. }
  40743. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  40744. /**
  40745. * Gets the global Hue value.
  40746. * 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).
  40747. */
  40748. get: function () {
  40749. return this._globalHue;
  40750. },
  40751. /**
  40752. * Sets the global Hue value.
  40753. * 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).
  40754. */
  40755. set: function (value) {
  40756. this._globalHue = value;
  40757. this._dirty = true;
  40758. },
  40759. enumerable: true,
  40760. configurable: true
  40761. });
  40762. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  40763. /**
  40764. * Gets the global Density value.
  40765. * 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.
  40766. * Values less than zero provide a filter of opposite hue.
  40767. */
  40768. get: function () {
  40769. return this._globalDensity;
  40770. },
  40771. /**
  40772. * Sets the global Density value.
  40773. * 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.
  40774. * Values less than zero provide a filter of opposite hue.
  40775. */
  40776. set: function (value) {
  40777. this._globalDensity = value;
  40778. this._dirty = true;
  40779. },
  40780. enumerable: true,
  40781. configurable: true
  40782. });
  40783. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  40784. /**
  40785. * Gets the global Saturation value.
  40786. * 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.
  40787. */
  40788. get: function () {
  40789. return this._globalSaturation;
  40790. },
  40791. /**
  40792. * Sets the global Saturation value.
  40793. * 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.
  40794. */
  40795. set: function (value) {
  40796. this._globalSaturation = value;
  40797. this._dirty = true;
  40798. },
  40799. enumerable: true,
  40800. configurable: true
  40801. });
  40802. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  40803. /**
  40804. * Gets the highlights Hue value.
  40805. * 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).
  40806. */
  40807. get: function () {
  40808. return this._highlightsHue;
  40809. },
  40810. /**
  40811. * Sets the highlights Hue value.
  40812. * 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).
  40813. */
  40814. set: function (value) {
  40815. this._highlightsHue = value;
  40816. this._dirty = true;
  40817. },
  40818. enumerable: true,
  40819. configurable: true
  40820. });
  40821. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  40822. /**
  40823. * Gets the highlights Density value.
  40824. * 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.
  40825. * Values less than zero provide a filter of opposite hue.
  40826. */
  40827. get: function () {
  40828. return this._highlightsDensity;
  40829. },
  40830. /**
  40831. * Sets the highlights Density value.
  40832. * 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.
  40833. * Values less than zero provide a filter of opposite hue.
  40834. */
  40835. set: function (value) {
  40836. this._highlightsDensity = value;
  40837. this._dirty = true;
  40838. },
  40839. enumerable: true,
  40840. configurable: true
  40841. });
  40842. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  40843. /**
  40844. * Gets the highlights Saturation value.
  40845. * 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.
  40846. */
  40847. get: function () {
  40848. return this._highlightsSaturation;
  40849. },
  40850. /**
  40851. * Sets the highlights Saturation value.
  40852. * 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.
  40853. */
  40854. set: function (value) {
  40855. this._highlightsSaturation = value;
  40856. this._dirty = true;
  40857. },
  40858. enumerable: true,
  40859. configurable: true
  40860. });
  40861. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  40862. /**
  40863. * Gets the highlights Exposure value.
  40864. * 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.
  40865. */
  40866. get: function () {
  40867. return this._highlightsExposure;
  40868. },
  40869. /**
  40870. * Sets the highlights Exposure value.
  40871. * 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.
  40872. */
  40873. set: function (value) {
  40874. this._highlightsExposure = value;
  40875. this._dirty = true;
  40876. },
  40877. enumerable: true,
  40878. configurable: true
  40879. });
  40880. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  40881. /**
  40882. * Gets the midtones Hue value.
  40883. * 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).
  40884. */
  40885. get: function () {
  40886. return this._midtonesHue;
  40887. },
  40888. /**
  40889. * Sets the midtones Hue value.
  40890. * 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).
  40891. */
  40892. set: function (value) {
  40893. this._midtonesHue = value;
  40894. this._dirty = true;
  40895. },
  40896. enumerable: true,
  40897. configurable: true
  40898. });
  40899. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  40900. /**
  40901. * Gets the midtones Density value.
  40902. * 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.
  40903. * Values less than zero provide a filter of opposite hue.
  40904. */
  40905. get: function () {
  40906. return this._midtonesDensity;
  40907. },
  40908. /**
  40909. * Sets the midtones Density value.
  40910. * 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.
  40911. * Values less than zero provide a filter of opposite hue.
  40912. */
  40913. set: function (value) {
  40914. this._midtonesDensity = value;
  40915. this._dirty = true;
  40916. },
  40917. enumerable: true,
  40918. configurable: true
  40919. });
  40920. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  40921. /**
  40922. * Gets the midtones Saturation value.
  40923. * 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.
  40924. */
  40925. get: function () {
  40926. return this._midtonesSaturation;
  40927. },
  40928. /**
  40929. * Sets the midtones Saturation value.
  40930. * 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.
  40931. */
  40932. set: function (value) {
  40933. this._midtonesSaturation = value;
  40934. this._dirty = true;
  40935. },
  40936. enumerable: true,
  40937. configurable: true
  40938. });
  40939. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  40940. /**
  40941. * Gets the midtones Exposure value.
  40942. * 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.
  40943. */
  40944. get: function () {
  40945. return this._midtonesExposure;
  40946. },
  40947. /**
  40948. * Sets the midtones Exposure value.
  40949. * 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.
  40950. */
  40951. set: function (value) {
  40952. this._midtonesExposure = value;
  40953. this._dirty = true;
  40954. },
  40955. enumerable: true,
  40956. configurable: true
  40957. });
  40958. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  40959. /**
  40960. * Gets the shadows Hue value.
  40961. * 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).
  40962. */
  40963. get: function () {
  40964. return this._shadowsHue;
  40965. },
  40966. /**
  40967. * Sets the shadows Hue value.
  40968. * 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).
  40969. */
  40970. set: function (value) {
  40971. this._shadowsHue = value;
  40972. this._dirty = true;
  40973. },
  40974. enumerable: true,
  40975. configurable: true
  40976. });
  40977. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  40978. /**
  40979. * Gets the shadows Density value.
  40980. * 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.
  40981. * Values less than zero provide a filter of opposite hue.
  40982. */
  40983. get: function () {
  40984. return this._shadowsDensity;
  40985. },
  40986. /**
  40987. * Sets the shadows Density value.
  40988. * 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.
  40989. * Values less than zero provide a filter of opposite hue.
  40990. */
  40991. set: function (value) {
  40992. this._shadowsDensity = value;
  40993. this._dirty = true;
  40994. },
  40995. enumerable: true,
  40996. configurable: true
  40997. });
  40998. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  40999. /**
  41000. * Gets the shadows Saturation value.
  41001. * 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.
  41002. */
  41003. get: function () {
  41004. return this._shadowsSaturation;
  41005. },
  41006. /**
  41007. * Sets the shadows Saturation value.
  41008. * 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.
  41009. */
  41010. set: function (value) {
  41011. this._shadowsSaturation = value;
  41012. this._dirty = true;
  41013. },
  41014. enumerable: true,
  41015. configurable: true
  41016. });
  41017. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41018. /**
  41019. * Gets the shadows Exposure value.
  41020. * 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.
  41021. */
  41022. get: function () {
  41023. return this._shadowsExposure;
  41024. },
  41025. /**
  41026. * Sets the shadows Exposure value.
  41027. * 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.
  41028. */
  41029. set: function (value) {
  41030. this._shadowsExposure = value;
  41031. this._dirty = true;
  41032. },
  41033. enumerable: true,
  41034. configurable: true
  41035. });
  41036. ColorCurves.prototype.getClassName = function () {
  41037. return "ColorCurves";
  41038. };
  41039. /**
  41040. * Binds the color curves to the shader.
  41041. * @param colorCurves The color curve to bind
  41042. * @param effect The effect to bind to
  41043. */
  41044. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41045. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41046. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41047. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41048. if (colorCurves._dirty) {
  41049. colorCurves._dirty = false;
  41050. // Fill in global info.
  41051. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41052. // Compute highlights info.
  41053. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41054. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41055. // Compute midtones info.
  41056. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41057. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41058. // Compute shadows info.
  41059. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41060. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41061. // Compute deltas (neutral is midtones).
  41062. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41063. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41064. }
  41065. if (effect) {
  41066. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41067. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41068. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41069. }
  41070. };
  41071. /**
  41072. * Prepare the list of uniforms associated with the ColorCurves effects.
  41073. * @param uniformsList The list of uniforms used in the effect
  41074. */
  41075. ColorCurves.PrepareUniforms = function (uniformsList) {
  41076. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41077. };
  41078. /**
  41079. * Returns color grading data based on a hue, density, saturation and exposure value.
  41080. * @param filterHue The hue of the color filter.
  41081. * @param filterDensity The density of the color filter.
  41082. * @param saturation The saturation.
  41083. * @param exposure The exposure.
  41084. * @param result The result data container.
  41085. */
  41086. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41087. if (hue == null) {
  41088. return;
  41089. }
  41090. hue = ColorCurves.clamp(hue, 0, 360);
  41091. density = ColorCurves.clamp(density, -100, 100);
  41092. saturation = ColorCurves.clamp(saturation, -100, 100);
  41093. exposure = ColorCurves.clamp(exposure, -100, 100);
  41094. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41095. // so that the maximum filter density is only 50% control. This provides fine control
  41096. // for small values and reasonable range.
  41097. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41098. density *= 0.5;
  41099. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41100. if (density < 0) {
  41101. density *= -1;
  41102. hue = (hue + 180) % 360;
  41103. }
  41104. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41105. result.scaleToRef(2, result);
  41106. result.a = 1 + 0.01 * saturation;
  41107. };
  41108. /**
  41109. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41110. * @param value The input slider value in range [-100,100].
  41111. * @returns Adjusted value.
  41112. */
  41113. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41114. value /= 100;
  41115. var x = Math.abs(value);
  41116. x = Math.pow(x, 2);
  41117. if (value < 0) {
  41118. x *= -1;
  41119. }
  41120. x *= 100;
  41121. return x;
  41122. };
  41123. /**
  41124. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41125. * @param hue The hue (H) input.
  41126. * @param saturation The saturation (S) input.
  41127. * @param brightness The brightness (B) input.
  41128. * @result An RGBA color represented as Vector4.
  41129. */
  41130. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41131. var h = ColorCurves.clamp(hue, 0, 360);
  41132. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41133. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41134. if (s === 0) {
  41135. result.r = v;
  41136. result.g = v;
  41137. result.b = v;
  41138. }
  41139. else {
  41140. // sector 0 to 5
  41141. h /= 60;
  41142. var i = Math.floor(h);
  41143. // fractional part of h
  41144. var f = h - i;
  41145. var p = v * (1 - s);
  41146. var q = v * (1 - s * f);
  41147. var t = v * (1 - s * (1 - f));
  41148. switch (i) {
  41149. case 0:
  41150. result.r = v;
  41151. result.g = t;
  41152. result.b = p;
  41153. break;
  41154. case 1:
  41155. result.r = q;
  41156. result.g = v;
  41157. result.b = p;
  41158. break;
  41159. case 2:
  41160. result.r = p;
  41161. result.g = v;
  41162. result.b = t;
  41163. break;
  41164. case 3:
  41165. result.r = p;
  41166. result.g = q;
  41167. result.b = v;
  41168. break;
  41169. case 4:
  41170. result.r = t;
  41171. result.g = p;
  41172. result.b = v;
  41173. break;
  41174. default:// case 5:
  41175. result.r = v;
  41176. result.g = p;
  41177. result.b = q;
  41178. break;
  41179. }
  41180. }
  41181. result.a = 1;
  41182. };
  41183. /**
  41184. * Returns a value clamped between min and max
  41185. * @param value The value to clamp
  41186. * @param min The minimum of value
  41187. * @param max The maximum of value
  41188. * @returns The clamped value.
  41189. */
  41190. ColorCurves.clamp = function (value, min, max) {
  41191. return Math.min(Math.max(value, min), max);
  41192. };
  41193. /**
  41194. * Clones the current color curve instance.
  41195. * @return The cloned curves
  41196. */
  41197. ColorCurves.prototype.clone = function () {
  41198. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41199. };
  41200. /**
  41201. * Serializes the current color curve instance to a json representation.
  41202. * @return a JSON representation
  41203. */
  41204. ColorCurves.prototype.serialize = function () {
  41205. return BABYLON.SerializationHelper.Serialize(this);
  41206. };
  41207. /**
  41208. * Parses the color curve from a json representation.
  41209. * @param source the JSON source to parse
  41210. * @return The parsed curves
  41211. */
  41212. ColorCurves.Parse = function (source) {
  41213. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41214. };
  41215. __decorate([
  41216. BABYLON.serialize()
  41217. ], ColorCurves.prototype, "_globalHue", void 0);
  41218. __decorate([
  41219. BABYLON.serialize()
  41220. ], ColorCurves.prototype, "_globalDensity", void 0);
  41221. __decorate([
  41222. BABYLON.serialize()
  41223. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41224. __decorate([
  41225. BABYLON.serialize()
  41226. ], ColorCurves.prototype, "_globalExposure", void 0);
  41227. __decorate([
  41228. BABYLON.serialize()
  41229. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41230. __decorate([
  41231. BABYLON.serialize()
  41232. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41233. __decorate([
  41234. BABYLON.serialize()
  41235. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41236. __decorate([
  41237. BABYLON.serialize()
  41238. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41239. __decorate([
  41240. BABYLON.serialize()
  41241. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41242. __decorate([
  41243. BABYLON.serialize()
  41244. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41245. __decorate([
  41246. BABYLON.serialize()
  41247. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41248. __decorate([
  41249. BABYLON.serialize()
  41250. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41251. return ColorCurves;
  41252. }());
  41253. BABYLON.ColorCurves = ColorCurves;
  41254. })(BABYLON || (BABYLON = {}));
  41255. //# sourceMappingURL=babylon.colorCurves.js.map
  41256. "use strict";
  41257. //# sourceMappingURL=babylon.behavior.js.map
  41258. "use strict";
  41259. var BABYLON;
  41260. (function (BABYLON) {
  41261. /**
  41262. * "Static Class" containing the most commonly used helper while dealing with material for
  41263. * rendering purpose.
  41264. *
  41265. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41266. *
  41267. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41268. */
  41269. var MaterialHelper = /** @class */ (function () {
  41270. function MaterialHelper() {
  41271. }
  41272. /**
  41273. * Bind the current view position to an effect.
  41274. * @param effect The effect to be bound
  41275. * @param scene The scene the eyes position is used from
  41276. */
  41277. MaterialHelper.BindEyePosition = function (effect, scene) {
  41278. if (scene._forcedViewPosition) {
  41279. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41280. return;
  41281. }
  41282. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41283. };
  41284. /**
  41285. * Helps preparing the defines values about the UVs in used in the effect.
  41286. * UVs are shared as much as we can accross chanels in the shaders.
  41287. * @param texture The texture we are preparing the UVs for
  41288. * @param defines The defines to update
  41289. * @param key The chanel key "diffuse", "specular"... used in the shader
  41290. */
  41291. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41292. defines._needUVs = true;
  41293. defines[key] = true;
  41294. if (texture.getTextureMatrix().isIdentity(true)) {
  41295. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41296. if (texture.coordinatesIndex === 0) {
  41297. defines["MAINUV1"] = true;
  41298. }
  41299. else {
  41300. defines["MAINUV2"] = true;
  41301. }
  41302. }
  41303. else {
  41304. defines[key + "DIRECTUV"] = 0;
  41305. }
  41306. };
  41307. /**
  41308. * Binds a texture matrix value to its corrsponding uniform
  41309. * @param texture The texture to bind the matrix for
  41310. * @param uniformBuffer The uniform buffer receivin the data
  41311. * @param key The chanel key "diffuse", "specular"... used in the shader
  41312. */
  41313. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41314. var matrix = texture.getTextureMatrix();
  41315. if (!matrix.isIdentity(true)) {
  41316. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41317. }
  41318. };
  41319. /**
  41320. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41321. * @param mesh defines the current mesh
  41322. * @param scene defines the current scene
  41323. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41324. * @param pointsCloud defines if point cloud rendering has to be turned on
  41325. * @param fogEnabled defines if fog has to be turned on
  41326. * @param alphaTest defines if alpha testing has to be turned on
  41327. * @param defines defines the current list of defines
  41328. */
  41329. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41330. if (defines._areMiscDirty) {
  41331. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41332. defines["POINTSIZE"] = pointsCloud;
  41333. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41334. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41335. defines["ALPHATEST"] = alphaTest;
  41336. }
  41337. };
  41338. /**
  41339. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41340. * @param scene defines the current scene
  41341. * @param engine defines the current engine
  41342. * @param defines specifies the list of active defines
  41343. * @param useInstances defines if instances have to be turned on
  41344. * @param useClipPlane defines if clip plane have to be turned on
  41345. */
  41346. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41347. if (useClipPlane === void 0) { useClipPlane = null; }
  41348. var changed = false;
  41349. if (useClipPlane == null) {
  41350. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41351. }
  41352. if (defines["CLIPPLANE"] !== useClipPlane) {
  41353. defines["CLIPPLANE"] = useClipPlane;
  41354. changed = true;
  41355. }
  41356. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41357. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41358. changed = true;
  41359. }
  41360. if (defines["INSTANCES"] !== useInstances) {
  41361. defines["INSTANCES"] = useInstances;
  41362. changed = true;
  41363. }
  41364. if (changed) {
  41365. defines.markAsUnprocessed();
  41366. }
  41367. };
  41368. /**
  41369. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41370. * @param mesh The mesh containing the geometry data we will draw
  41371. * @param defines The defines to update
  41372. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41373. * @param useBones Precise whether bones should be used or not (override mesh info)
  41374. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41375. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41376. * @returns false if defines are considered not dirty and have not been checked
  41377. */
  41378. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41379. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41380. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41381. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41382. return false;
  41383. }
  41384. defines._normals = defines._needNormals;
  41385. defines._uvs = defines._needUVs;
  41386. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41387. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41388. defines["TANGENT"] = true;
  41389. }
  41390. if (defines._needUVs) {
  41391. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41392. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41393. }
  41394. else {
  41395. defines["UV1"] = false;
  41396. defines["UV2"] = false;
  41397. }
  41398. if (useVertexColor) {
  41399. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41400. defines["VERTEXCOLOR"] = hasVertexColors;
  41401. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41402. }
  41403. if (useBones) {
  41404. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41405. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41406. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41407. }
  41408. else {
  41409. defines["NUM_BONE_INFLUENCERS"] = 0;
  41410. defines["BonesPerMesh"] = 0;
  41411. }
  41412. }
  41413. if (useMorphTargets) {
  41414. var manager = mesh.morphTargetManager;
  41415. if (manager) {
  41416. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41417. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41418. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41419. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41420. }
  41421. else {
  41422. defines["MORPHTARGETS_TANGENT"] = false;
  41423. defines["MORPHTARGETS_NORMAL"] = false;
  41424. defines["MORPHTARGETS"] = false;
  41425. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41426. }
  41427. }
  41428. return true;
  41429. };
  41430. /**
  41431. * Prepares the defines related to the light information passed in parameter
  41432. * @param scene The scene we are intending to draw
  41433. * @param mesh The mesh the effect is compiling for
  41434. * @param defines The defines to update
  41435. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41436. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41437. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41438. * @returns true if normals will be required for the rest of the effect
  41439. */
  41440. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41441. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41442. if (disableLighting === void 0) { disableLighting = false; }
  41443. if (!defines._areLightsDirty) {
  41444. return defines._needNormals;
  41445. }
  41446. var lightIndex = 0;
  41447. var needNormals = false;
  41448. var needRebuild = false;
  41449. var lightmapMode = false;
  41450. var shadowEnabled = false;
  41451. var specularEnabled = false;
  41452. if (scene.lightsEnabled && !disableLighting) {
  41453. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41454. var light = _a[_i];
  41455. needNormals = true;
  41456. if (defines["LIGHT" + lightIndex] === undefined) {
  41457. needRebuild = true;
  41458. }
  41459. defines["LIGHT" + lightIndex] = true;
  41460. defines["SPOTLIGHT" + lightIndex] = false;
  41461. defines["HEMILIGHT" + lightIndex] = false;
  41462. defines["POINTLIGHT" + lightIndex] = false;
  41463. defines["DIRLIGHT" + lightIndex] = false;
  41464. var type;
  41465. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41466. type = "SPOTLIGHT" + lightIndex;
  41467. var spotLight = light;
  41468. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  41469. }
  41470. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41471. type = "HEMILIGHT" + lightIndex;
  41472. }
  41473. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41474. type = "POINTLIGHT" + lightIndex;
  41475. }
  41476. else {
  41477. type = "DIRLIGHT" + lightIndex;
  41478. }
  41479. defines[type] = true;
  41480. // Specular
  41481. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41482. specularEnabled = true;
  41483. }
  41484. // Shadows
  41485. defines["SHADOW" + lightIndex] = false;
  41486. defines["SHADOWPCF" + lightIndex] = false;
  41487. defines["SHADOWPCSS" + lightIndex] = false;
  41488. defines["SHADOWPOISSON" + lightIndex] = false;
  41489. defines["SHADOWESM" + lightIndex] = false;
  41490. defines["SHADOWCUBE" + lightIndex] = false;
  41491. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41492. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41493. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41494. var shadowGenerator = light.getShadowGenerator();
  41495. if (shadowGenerator) {
  41496. shadowEnabled = true;
  41497. shadowGenerator.prepareDefines(defines, lightIndex);
  41498. }
  41499. }
  41500. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41501. lightmapMode = true;
  41502. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41503. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41504. }
  41505. else {
  41506. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41507. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41508. }
  41509. lightIndex++;
  41510. if (lightIndex === maxSimultaneousLights)
  41511. break;
  41512. }
  41513. }
  41514. defines["SPECULARTERM"] = specularEnabled;
  41515. defines["SHADOWS"] = shadowEnabled;
  41516. // Resetting all other lights if any
  41517. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41518. if (defines["LIGHT" + index] !== undefined) {
  41519. defines["LIGHT" + index] = false;
  41520. defines["HEMILIGHT" + lightIndex] = false;
  41521. defines["POINTLIGHT" + lightIndex] = false;
  41522. defines["DIRLIGHT" + lightIndex] = false;
  41523. defines["SPOTLIGHT" + lightIndex] = false;
  41524. defines["SHADOW" + lightIndex] = false;
  41525. }
  41526. }
  41527. var caps = scene.getEngine().getCaps();
  41528. if (defines["SHADOWFLOAT"] === undefined) {
  41529. needRebuild = true;
  41530. }
  41531. defines["SHADOWFLOAT"] = shadowEnabled &&
  41532. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41533. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41534. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41535. if (needRebuild) {
  41536. defines.rebuild();
  41537. }
  41538. return needNormals;
  41539. };
  41540. /**
  41541. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41542. * that won t be acctive due to defines being turned off.
  41543. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41544. * @param samplersList The samplers list
  41545. * @param defines The defines helping in the list generation
  41546. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41547. */
  41548. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41549. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41550. var uniformsList;
  41551. var uniformBuffersList = null;
  41552. if (uniformsListOrOptions.uniformsNames) {
  41553. var options = uniformsListOrOptions;
  41554. uniformsList = options.uniformsNames;
  41555. uniformBuffersList = options.uniformBuffersNames;
  41556. samplersList = options.samplers;
  41557. defines = options.defines;
  41558. maxSimultaneousLights = options.maxSimultaneousLights;
  41559. }
  41560. else {
  41561. uniformsList = uniformsListOrOptions;
  41562. if (!samplersList) {
  41563. samplersList = [];
  41564. }
  41565. }
  41566. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41567. if (!defines["LIGHT" + lightIndex]) {
  41568. break;
  41569. }
  41570. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41571. if (uniformBuffersList) {
  41572. uniformBuffersList.push("Light" + lightIndex);
  41573. }
  41574. samplersList.push("shadowSampler" + lightIndex);
  41575. samplersList.push("depthSampler" + lightIndex);
  41576. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41577. samplersList.push("projectionLightSampler" + lightIndex);
  41578. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41579. }
  41580. }
  41581. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41582. uniformsList.push("morphTargetInfluences");
  41583. }
  41584. };
  41585. /**
  41586. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41587. * @param defines The defines to update while falling back
  41588. * @param fallbacks The authorized effect fallbacks
  41589. * @param maxSimultaneousLights The maximum number of lights allowed
  41590. * @param rank the current rank of the Effect
  41591. * @returns The newly affected rank
  41592. */
  41593. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41594. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41595. if (rank === void 0) { rank = 0; }
  41596. var lightFallbackRank = 0;
  41597. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41598. if (!defines["LIGHT" + lightIndex]) {
  41599. break;
  41600. }
  41601. if (lightIndex > 0) {
  41602. lightFallbackRank = rank + lightIndex;
  41603. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41604. }
  41605. if (!defines["SHADOWS"]) {
  41606. if (defines["SHADOW" + lightIndex]) {
  41607. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41608. }
  41609. if (defines["SHADOWPCF" + lightIndex]) {
  41610. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41611. }
  41612. if (defines["SHADOWPCSS" + lightIndex]) {
  41613. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41614. }
  41615. if (defines["SHADOWPOISSON" + lightIndex]) {
  41616. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41617. }
  41618. if (defines["SHADOWESM" + lightIndex]) {
  41619. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41620. }
  41621. }
  41622. }
  41623. return lightFallbackRank++;
  41624. };
  41625. /**
  41626. * Prepares the list of attributes required for morph targets according to the effect defines.
  41627. * @param attribs The current list of supported attribs
  41628. * @param mesh The mesh to prepare the morph targets attributes for
  41629. * @param defines The current Defines of the effect
  41630. */
  41631. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41632. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41633. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41634. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41635. var manager = mesh.morphTargetManager;
  41636. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41637. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41638. for (var index = 0; index < influencers; index++) {
  41639. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41640. if (normal) {
  41641. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41642. }
  41643. if (tangent) {
  41644. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41645. }
  41646. if (attribs.length > maxAttributesCount) {
  41647. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41648. }
  41649. }
  41650. }
  41651. };
  41652. /**
  41653. * Prepares the list of attributes required for bones according to the effect defines.
  41654. * @param attribs The current list of supported attribs
  41655. * @param mesh The mesh to prepare the bones attributes for
  41656. * @param defines The current Defines of the effect
  41657. * @param fallbacks The current efffect fallback strategy
  41658. */
  41659. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41660. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41661. fallbacks.addCPUSkinningFallback(0, mesh);
  41662. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41663. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41664. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41665. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41666. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41667. }
  41668. }
  41669. };
  41670. /**
  41671. * Prepares the list of attributes required for instances according to the effect defines.
  41672. * @param attribs The current list of supported attribs
  41673. * @param defines The current Defines of the effect
  41674. */
  41675. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41676. if (defines["INSTANCES"]) {
  41677. attribs.push("world0");
  41678. attribs.push("world1");
  41679. attribs.push("world2");
  41680. attribs.push("world3");
  41681. }
  41682. };
  41683. /**
  41684. * Binds the light shadow information to the effect for the given mesh.
  41685. * @param light The light containing the generator
  41686. * @param scene The scene the lights belongs to
  41687. * @param mesh The mesh we are binding the information to render
  41688. * @param lightIndex The light index in the effect used to render the mesh
  41689. * @param effect The effect we are binding the data to
  41690. */
  41691. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41692. if (light.shadowEnabled && mesh.receiveShadows) {
  41693. var shadowGenerator = light.getShadowGenerator();
  41694. if (shadowGenerator) {
  41695. shadowGenerator.bindShadowLight(lightIndex, effect);
  41696. }
  41697. }
  41698. };
  41699. /**
  41700. * Binds the light information to the effect.
  41701. * @param light The light containing the generator
  41702. * @param effect The effect we are binding the data to
  41703. * @param lightIndex The light index in the effect used to render
  41704. */
  41705. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41706. light.transferToEffect(effect, lightIndex + "");
  41707. };
  41708. /**
  41709. * Binds the lights information from the scene to the effect for the given mesh.
  41710. * @param scene The scene the lights belongs to
  41711. * @param mesh The mesh we are binding the information to render
  41712. * @param effect The effect we are binding the data to
  41713. * @param defines The generated defines for the effect
  41714. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41715. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41716. */
  41717. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41718. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41719. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41720. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41721. for (var i = 0; i < len; i++) {
  41722. var light = mesh._lightSources[i];
  41723. var iAsString = i.toString();
  41724. var scaledIntensity = light.getScaledIntensity();
  41725. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41726. MaterialHelper.BindLightProperties(light, effect, i);
  41727. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41728. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41729. if (defines["SPECULARTERM"]) {
  41730. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41731. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41732. }
  41733. // Shadows
  41734. if (scene.shadowsEnabled) {
  41735. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41736. }
  41737. light._uniformBuffer.update();
  41738. }
  41739. };
  41740. /**
  41741. * Binds the fog information from the scene to the effect for the given mesh.
  41742. * @param scene The scene the lights belongs to
  41743. * @param mesh The mesh we are binding the information to render
  41744. * @param effect The effect we are binding the data to
  41745. */
  41746. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41747. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41748. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41749. effect.setColor3("vFogColor", scene.fogColor);
  41750. }
  41751. };
  41752. /**
  41753. * Binds the bones information from the mesh to the effect.
  41754. * @param mesh The mesh we are binding the information to render
  41755. * @param effect The effect we are binding the data to
  41756. */
  41757. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41758. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41759. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41760. if (matrices && effect) {
  41761. effect.setMatrices("mBones", matrices);
  41762. }
  41763. }
  41764. };
  41765. /**
  41766. * Binds the morph targets information from the mesh to the effect.
  41767. * @param abstractMesh The mesh we are binding the information to render
  41768. * @param effect The effect we are binding the data to
  41769. */
  41770. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41771. var manager = abstractMesh.morphTargetManager;
  41772. if (!abstractMesh || !manager) {
  41773. return;
  41774. }
  41775. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41776. };
  41777. /**
  41778. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41779. * @param defines The generated defines used in the effect
  41780. * @param effect The effect we are binding the data to
  41781. * @param scene The scene we are willing to render with logarithmic scale for
  41782. */
  41783. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41784. if (defines["LOGARITHMICDEPTH"]) {
  41785. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41786. }
  41787. };
  41788. /**
  41789. * Binds the clip plane information from the scene to the effect.
  41790. * @param scene The scene the clip plane information are extracted from
  41791. * @param effect The effect we are binding the data to
  41792. */
  41793. MaterialHelper.BindClipPlane = function (effect, scene) {
  41794. if (scene.clipPlane) {
  41795. var clipPlane = scene.clipPlane;
  41796. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41797. }
  41798. };
  41799. return MaterialHelper;
  41800. }());
  41801. BABYLON.MaterialHelper = MaterialHelper;
  41802. })(BABYLON || (BABYLON = {}));
  41803. //# sourceMappingURL=babylon.materialHelper.js.map
  41804. "use strict";
  41805. var BABYLON;
  41806. (function (BABYLON) {
  41807. var PushMaterial = /** @class */ (function (_super) {
  41808. __extends(PushMaterial, _super);
  41809. function PushMaterial(name, scene) {
  41810. var _this = _super.call(this, name, scene) || this;
  41811. _this._normalMatrix = new BABYLON.Matrix();
  41812. _this.storeEffectOnSubMeshes = true;
  41813. return _this;
  41814. }
  41815. PushMaterial.prototype.getEffect = function () {
  41816. return this._activeEffect;
  41817. };
  41818. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41819. if (!mesh) {
  41820. return false;
  41821. }
  41822. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41823. return true;
  41824. }
  41825. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41826. };
  41827. /**
  41828. * Binds the given world matrix to the active effect
  41829. *
  41830. * @param world the matrix to bind
  41831. */
  41832. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41833. this._activeEffect.setMatrix("world", world);
  41834. };
  41835. /**
  41836. * Binds the given normal matrix to the active effect
  41837. *
  41838. * @param normalMatrix the matrix to bind
  41839. */
  41840. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41841. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41842. };
  41843. PushMaterial.prototype.bind = function (world, mesh) {
  41844. if (!mesh) {
  41845. return;
  41846. }
  41847. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41848. };
  41849. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41850. if (effect === void 0) { effect = null; }
  41851. _super.prototype._afterBind.call(this, mesh);
  41852. this.getScene()._cachedEffect = effect;
  41853. };
  41854. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41855. if (visibility === void 0) { visibility = 1; }
  41856. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41857. };
  41858. return PushMaterial;
  41859. }(BABYLON.Material));
  41860. BABYLON.PushMaterial = PushMaterial;
  41861. })(BABYLON || (BABYLON = {}));
  41862. //# sourceMappingURL=babylon.pushMaterial.js.map
  41863. "use strict";
  41864. var BABYLON;
  41865. (function (BABYLON) {
  41866. /** @ignore */
  41867. var StandardMaterialDefines = /** @class */ (function (_super) {
  41868. __extends(StandardMaterialDefines, _super);
  41869. function StandardMaterialDefines() {
  41870. var _this = _super.call(this) || this;
  41871. _this.MAINUV1 = false;
  41872. _this.MAINUV2 = false;
  41873. _this.DIFFUSE = false;
  41874. _this.DIFFUSEDIRECTUV = 0;
  41875. _this.AMBIENT = false;
  41876. _this.AMBIENTDIRECTUV = 0;
  41877. _this.OPACITY = false;
  41878. _this.OPACITYDIRECTUV = 0;
  41879. _this.OPACITYRGB = false;
  41880. _this.REFLECTION = false;
  41881. _this.EMISSIVE = false;
  41882. _this.EMISSIVEDIRECTUV = 0;
  41883. _this.SPECULAR = false;
  41884. _this.SPECULARDIRECTUV = 0;
  41885. _this.BUMP = false;
  41886. _this.BUMPDIRECTUV = 0;
  41887. _this.PARALLAX = false;
  41888. _this.PARALLAXOCCLUSION = false;
  41889. _this.SPECULAROVERALPHA = false;
  41890. _this.CLIPPLANE = false;
  41891. _this.ALPHATEST = false;
  41892. _this.DEPTHPREPASS = false;
  41893. _this.ALPHAFROMDIFFUSE = false;
  41894. _this.POINTSIZE = false;
  41895. _this.FOG = false;
  41896. _this.SPECULARTERM = false;
  41897. _this.DIFFUSEFRESNEL = false;
  41898. _this.OPACITYFRESNEL = false;
  41899. _this.REFLECTIONFRESNEL = false;
  41900. _this.REFRACTIONFRESNEL = false;
  41901. _this.EMISSIVEFRESNEL = false;
  41902. _this.FRESNEL = false;
  41903. _this.NORMAL = false;
  41904. _this.UV1 = false;
  41905. _this.UV2 = false;
  41906. _this.VERTEXCOLOR = false;
  41907. _this.VERTEXALPHA = false;
  41908. _this.NUM_BONE_INFLUENCERS = 0;
  41909. _this.BonesPerMesh = 0;
  41910. _this.INSTANCES = false;
  41911. _this.GLOSSINESS = false;
  41912. _this.ROUGHNESS = false;
  41913. _this.EMISSIVEASILLUMINATION = false;
  41914. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41915. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41916. _this.LIGHTMAP = false;
  41917. _this.LIGHTMAPDIRECTUV = 0;
  41918. _this.OBJECTSPACE_NORMALMAP = false;
  41919. _this.USELIGHTMAPASSHADOWMAP = false;
  41920. _this.REFLECTIONMAP_3D = false;
  41921. _this.REFLECTIONMAP_SPHERICAL = false;
  41922. _this.REFLECTIONMAP_PLANAR = false;
  41923. _this.REFLECTIONMAP_CUBIC = false;
  41924. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41925. _this.REFLECTIONMAP_PROJECTION = false;
  41926. _this.REFLECTIONMAP_SKYBOX = false;
  41927. _this.REFLECTIONMAP_EXPLICIT = false;
  41928. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41929. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41930. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41931. _this.INVERTCUBICMAP = false;
  41932. _this.LOGARITHMICDEPTH = false;
  41933. _this.REFRACTION = false;
  41934. _this.REFRACTIONMAP_3D = false;
  41935. _this.REFLECTIONOVERALPHA = false;
  41936. _this.TWOSIDEDLIGHTING = false;
  41937. _this.SHADOWFLOAT = false;
  41938. _this.MORPHTARGETS = false;
  41939. _this.MORPHTARGETS_NORMAL = false;
  41940. _this.MORPHTARGETS_TANGENT = false;
  41941. _this.NUM_MORPH_INFLUENCERS = 0;
  41942. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41943. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41944. _this.IMAGEPROCESSING = false;
  41945. _this.VIGNETTE = false;
  41946. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41947. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41948. _this.TONEMAPPING = false;
  41949. _this.CONTRAST = false;
  41950. _this.COLORCURVES = false;
  41951. _this.COLORGRADING = false;
  41952. _this.COLORGRADING3D = false;
  41953. _this.SAMPLER3DGREENDEPTH = false;
  41954. _this.SAMPLER3DBGRMAP = false;
  41955. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41956. _this.EXPOSURE = false;
  41957. _this.rebuild();
  41958. return _this;
  41959. }
  41960. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41961. var modes = [
  41962. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41963. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41964. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41965. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41966. ];
  41967. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41968. var mode = modes_1[_i];
  41969. this[mode] = (mode === modeToEnable);
  41970. }
  41971. };
  41972. return StandardMaterialDefines;
  41973. }(BABYLON.MaterialDefines));
  41974. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41975. var StandardMaterial = /** @class */ (function (_super) {
  41976. __extends(StandardMaterial, _super);
  41977. function StandardMaterial(name, scene) {
  41978. var _this = _super.call(this, name, scene) || this;
  41979. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41980. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41981. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41982. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41983. _this.specularPower = 64;
  41984. _this._useAlphaFromDiffuseTexture = false;
  41985. _this._useEmissiveAsIllumination = false;
  41986. _this._linkEmissiveWithDiffuse = false;
  41987. _this._useSpecularOverAlpha = false;
  41988. _this._useReflectionOverAlpha = false;
  41989. _this._disableLighting = false;
  41990. _this._useObjectSpaceNormalMap = false;
  41991. _this._useParallax = false;
  41992. _this._useParallaxOcclusion = false;
  41993. _this.parallaxScaleBias = 0.05;
  41994. _this._roughness = 0;
  41995. _this.indexOfRefraction = 0.98;
  41996. _this.invertRefractionY = true;
  41997. _this._useLightmapAsShadowmap = false;
  41998. _this._useReflectionFresnelFromSpecular = false;
  41999. _this._useGlossinessFromSpecularMapAlpha = false;
  42000. _this._maxSimultaneousLights = 4;
  42001. /**
  42002. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42003. */
  42004. _this._invertNormalMapX = false;
  42005. /**
  42006. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42007. */
  42008. _this._invertNormalMapY = false;
  42009. /**
  42010. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42011. */
  42012. _this._twoSidedLighting = false;
  42013. _this._renderTargets = new BABYLON.SmartArray(16);
  42014. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42015. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42016. // Setup the default processing configuration to the scene.
  42017. _this._attachImageProcessingConfiguration(null);
  42018. _this.getRenderTargetTextures = function () {
  42019. _this._renderTargets.reset();
  42020. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42021. _this._renderTargets.push(_this._reflectionTexture);
  42022. }
  42023. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42024. _this._renderTargets.push(_this._refractionTexture);
  42025. }
  42026. return _this._renderTargets;
  42027. };
  42028. return _this;
  42029. }
  42030. ;
  42031. ;
  42032. ;
  42033. ;
  42034. ;
  42035. ;
  42036. ;
  42037. ;
  42038. ;
  42039. ;
  42040. ;
  42041. ;
  42042. ;
  42043. ;
  42044. ;
  42045. ;
  42046. ;
  42047. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42048. /**
  42049. * Gets the image processing configuration used either in this material.
  42050. */
  42051. get: function () {
  42052. return this._imageProcessingConfiguration;
  42053. },
  42054. /**
  42055. * Sets the Default image processing configuration used either in the this material.
  42056. *
  42057. * If sets to null, the scene one is in use.
  42058. */
  42059. set: function (value) {
  42060. this._attachImageProcessingConfiguration(value);
  42061. // Ensure the effect will be rebuilt.
  42062. this._markAllSubMeshesAsTexturesDirty();
  42063. },
  42064. enumerable: true,
  42065. configurable: true
  42066. });
  42067. /**
  42068. * Attaches a new image processing configuration to the Standard Material.
  42069. * @param configuration
  42070. */
  42071. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42072. var _this = this;
  42073. if (configuration === this._imageProcessingConfiguration) {
  42074. return;
  42075. }
  42076. // Detaches observer.
  42077. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42078. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42079. }
  42080. // Pick the scene configuration if needed.
  42081. if (!configuration) {
  42082. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42083. }
  42084. else {
  42085. this._imageProcessingConfiguration = configuration;
  42086. }
  42087. // Attaches observer.
  42088. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42089. _this._markAllSubMeshesAsImageProcessingDirty();
  42090. });
  42091. };
  42092. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42093. /**
  42094. * Gets wether the color curves effect is enabled.
  42095. */
  42096. get: function () {
  42097. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42098. },
  42099. /**
  42100. * Sets wether the color curves effect is enabled.
  42101. */
  42102. set: function (value) {
  42103. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42104. },
  42105. enumerable: true,
  42106. configurable: true
  42107. });
  42108. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42109. /**
  42110. * Gets wether the color grading effect is enabled.
  42111. */
  42112. get: function () {
  42113. return this.imageProcessingConfiguration.colorGradingEnabled;
  42114. },
  42115. /**
  42116. * Gets wether the color grading effect is enabled.
  42117. */
  42118. set: function (value) {
  42119. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42120. },
  42121. enumerable: true,
  42122. configurable: true
  42123. });
  42124. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42125. /**
  42126. * Gets wether tonemapping is enabled or not.
  42127. */
  42128. get: function () {
  42129. return this._imageProcessingConfiguration.toneMappingEnabled;
  42130. },
  42131. /**
  42132. * Sets wether tonemapping is enabled or not
  42133. */
  42134. set: function (value) {
  42135. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42136. },
  42137. enumerable: true,
  42138. configurable: true
  42139. });
  42140. ;
  42141. ;
  42142. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42143. /**
  42144. * The camera exposure used on this material.
  42145. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42146. * This corresponds to a photographic exposure.
  42147. */
  42148. get: function () {
  42149. return this._imageProcessingConfiguration.exposure;
  42150. },
  42151. /**
  42152. * The camera exposure used on this material.
  42153. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42154. * This corresponds to a photographic exposure.
  42155. */
  42156. set: function (value) {
  42157. this._imageProcessingConfiguration.exposure = value;
  42158. },
  42159. enumerable: true,
  42160. configurable: true
  42161. });
  42162. ;
  42163. ;
  42164. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42165. /**
  42166. * Gets The camera contrast used on this material.
  42167. */
  42168. get: function () {
  42169. return this._imageProcessingConfiguration.contrast;
  42170. },
  42171. /**
  42172. * Sets The camera contrast used on this material.
  42173. */
  42174. set: function (value) {
  42175. this._imageProcessingConfiguration.contrast = value;
  42176. },
  42177. enumerable: true,
  42178. configurable: true
  42179. });
  42180. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42181. /**
  42182. * Gets the Color Grading 2D Lookup Texture.
  42183. */
  42184. get: function () {
  42185. return this._imageProcessingConfiguration.colorGradingTexture;
  42186. },
  42187. /**
  42188. * Sets the Color Grading 2D Lookup Texture.
  42189. */
  42190. set: function (value) {
  42191. this._imageProcessingConfiguration.colorGradingTexture = value;
  42192. },
  42193. enumerable: true,
  42194. configurable: true
  42195. });
  42196. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42197. /**
  42198. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42199. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42200. * 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;
  42201. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42202. */
  42203. get: function () {
  42204. return this._imageProcessingConfiguration.colorCurves;
  42205. },
  42206. /**
  42207. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42208. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42209. * 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;
  42210. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42211. */
  42212. set: function (value) {
  42213. this._imageProcessingConfiguration.colorCurves = value;
  42214. },
  42215. enumerable: true,
  42216. configurable: true
  42217. });
  42218. StandardMaterial.prototype.getClassName = function () {
  42219. return "StandardMaterial";
  42220. };
  42221. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42222. get: function () {
  42223. return this._useLogarithmicDepth;
  42224. },
  42225. set: function (value) {
  42226. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42227. this._markAllSubMeshesAsMiscDirty();
  42228. },
  42229. enumerable: true,
  42230. configurable: true
  42231. });
  42232. StandardMaterial.prototype.needAlphaBlending = function () {
  42233. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42234. };
  42235. StandardMaterial.prototype.needAlphaTesting = function () {
  42236. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42237. };
  42238. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42239. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42240. };
  42241. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42242. return this._diffuseTexture;
  42243. };
  42244. /**
  42245. * Child classes can use it to update shaders
  42246. */
  42247. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42248. if (useInstances === void 0) { useInstances = false; }
  42249. if (subMesh.effect && this.isFrozen) {
  42250. if (this._wasPreviouslyReady && subMesh.effect) {
  42251. return true;
  42252. }
  42253. }
  42254. if (!subMesh._materialDefines) {
  42255. subMesh._materialDefines = new StandardMaterialDefines();
  42256. }
  42257. var scene = this.getScene();
  42258. var defines = subMesh._materialDefines;
  42259. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42260. if (defines._renderId === scene.getRenderId()) {
  42261. return true;
  42262. }
  42263. }
  42264. var engine = scene.getEngine();
  42265. // Lights
  42266. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42267. // Textures
  42268. if (defines._areTexturesDirty) {
  42269. defines._needUVs = false;
  42270. defines.MAINUV1 = false;
  42271. defines.MAINUV2 = false;
  42272. if (scene.texturesEnabled) {
  42273. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42274. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42275. return false;
  42276. }
  42277. else {
  42278. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42279. }
  42280. }
  42281. else {
  42282. defines.DIFFUSE = false;
  42283. }
  42284. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42285. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42286. return false;
  42287. }
  42288. else {
  42289. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42290. }
  42291. }
  42292. else {
  42293. defines.AMBIENT = false;
  42294. }
  42295. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42296. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42297. return false;
  42298. }
  42299. else {
  42300. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42301. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42302. }
  42303. }
  42304. else {
  42305. defines.OPACITY = false;
  42306. }
  42307. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42308. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42309. return false;
  42310. }
  42311. else {
  42312. defines._needNormals = true;
  42313. defines.REFLECTION = true;
  42314. defines.ROUGHNESS = (this._roughness > 0);
  42315. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42316. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42317. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42318. switch (this._reflectionTexture.coordinatesMode) {
  42319. case BABYLON.Texture.CUBIC_MODE:
  42320. case BABYLON.Texture.INVCUBIC_MODE:
  42321. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42322. break;
  42323. case BABYLON.Texture.EXPLICIT_MODE:
  42324. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42325. break;
  42326. case BABYLON.Texture.PLANAR_MODE:
  42327. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42328. break;
  42329. case BABYLON.Texture.PROJECTION_MODE:
  42330. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42331. break;
  42332. case BABYLON.Texture.SKYBOX_MODE:
  42333. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42334. break;
  42335. case BABYLON.Texture.SPHERICAL_MODE:
  42336. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42337. break;
  42338. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42339. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42340. break;
  42341. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42342. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42343. break;
  42344. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42345. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42346. break;
  42347. }
  42348. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42349. }
  42350. }
  42351. else {
  42352. defines.REFLECTION = false;
  42353. }
  42354. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42355. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42356. return false;
  42357. }
  42358. else {
  42359. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42360. }
  42361. }
  42362. else {
  42363. defines.EMISSIVE = false;
  42364. }
  42365. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42366. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42367. return false;
  42368. }
  42369. else {
  42370. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42371. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42372. }
  42373. }
  42374. else {
  42375. defines.LIGHTMAP = false;
  42376. }
  42377. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42378. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42379. return false;
  42380. }
  42381. else {
  42382. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42383. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42384. }
  42385. }
  42386. else {
  42387. defines.SPECULAR = false;
  42388. }
  42389. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42390. // Bump texure can not be not blocking.
  42391. if (!this._bumpTexture.isReady()) {
  42392. return false;
  42393. }
  42394. else {
  42395. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42396. defines.PARALLAX = this._useParallax;
  42397. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42398. }
  42399. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42400. }
  42401. else {
  42402. defines.BUMP = false;
  42403. }
  42404. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42405. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42406. return false;
  42407. }
  42408. else {
  42409. defines._needUVs = true;
  42410. defines.REFRACTION = true;
  42411. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42412. }
  42413. }
  42414. else {
  42415. defines.REFRACTION = false;
  42416. }
  42417. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42418. }
  42419. else {
  42420. defines.DIFFUSE = false;
  42421. defines.AMBIENT = false;
  42422. defines.OPACITY = false;
  42423. defines.REFLECTION = false;
  42424. defines.EMISSIVE = false;
  42425. defines.LIGHTMAP = false;
  42426. defines.BUMP = false;
  42427. defines.REFRACTION = false;
  42428. }
  42429. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42430. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42431. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42432. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42433. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42434. }
  42435. if (defines._areImageProcessingDirty) {
  42436. if (!this._imageProcessingConfiguration.isReady()) {
  42437. return false;
  42438. }
  42439. this._imageProcessingConfiguration.prepareDefines(defines);
  42440. }
  42441. if (defines._areFresnelDirty) {
  42442. if (StandardMaterial.FresnelEnabled) {
  42443. // Fresnel
  42444. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42445. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42446. this._reflectionFresnelParameters) {
  42447. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42448. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42449. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42450. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42451. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42452. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42453. defines._needNormals = true;
  42454. defines.FRESNEL = true;
  42455. }
  42456. }
  42457. else {
  42458. defines.FRESNEL = false;
  42459. }
  42460. }
  42461. // Misc.
  42462. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42463. // Attribs
  42464. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42465. // Values that need to be evaluated on every frame
  42466. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42467. // Get correct effect
  42468. if (defines.isDirty) {
  42469. defines.markAsProcessed();
  42470. scene.resetCachedMaterial();
  42471. // Fallbacks
  42472. var fallbacks = new BABYLON.EffectFallbacks();
  42473. if (defines.REFLECTION) {
  42474. fallbacks.addFallback(0, "REFLECTION");
  42475. }
  42476. if (defines.SPECULAR) {
  42477. fallbacks.addFallback(0, "SPECULAR");
  42478. }
  42479. if (defines.BUMP) {
  42480. fallbacks.addFallback(0, "BUMP");
  42481. }
  42482. if (defines.PARALLAX) {
  42483. fallbacks.addFallback(1, "PARALLAX");
  42484. }
  42485. if (defines.PARALLAXOCCLUSION) {
  42486. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42487. }
  42488. if (defines.SPECULAROVERALPHA) {
  42489. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42490. }
  42491. if (defines.FOG) {
  42492. fallbacks.addFallback(1, "FOG");
  42493. }
  42494. if (defines.POINTSIZE) {
  42495. fallbacks.addFallback(0, "POINTSIZE");
  42496. }
  42497. if (defines.LOGARITHMICDEPTH) {
  42498. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42499. }
  42500. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42501. if (defines.SPECULARTERM) {
  42502. fallbacks.addFallback(0, "SPECULARTERM");
  42503. }
  42504. if (defines.DIFFUSEFRESNEL) {
  42505. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42506. }
  42507. if (defines.OPACITYFRESNEL) {
  42508. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42509. }
  42510. if (defines.REFLECTIONFRESNEL) {
  42511. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42512. }
  42513. if (defines.EMISSIVEFRESNEL) {
  42514. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42515. }
  42516. if (defines.FRESNEL) {
  42517. fallbacks.addFallback(4, "FRESNEL");
  42518. }
  42519. //Attributes
  42520. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42521. if (defines.NORMAL) {
  42522. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42523. }
  42524. if (defines.UV1) {
  42525. attribs.push(BABYLON.VertexBuffer.UVKind);
  42526. }
  42527. if (defines.UV2) {
  42528. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42529. }
  42530. if (defines.VERTEXCOLOR) {
  42531. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42532. }
  42533. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42534. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42535. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42536. var shaderName = "default";
  42537. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42538. "vFogInfos", "vFogColor", "pointSize",
  42539. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42540. "mBones",
  42541. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42542. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42543. "vReflectionPosition", "vReflectionSize",
  42544. "logarithmicDepthConstant", "vTangentSpaceParams"
  42545. ];
  42546. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42547. var uniformBuffers = ["Material", "Scene"];
  42548. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42549. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42550. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42551. uniformsNames: uniforms,
  42552. uniformBuffersNames: uniformBuffers,
  42553. samplers: samplers,
  42554. defines: defines,
  42555. maxSimultaneousLights: this._maxSimultaneousLights
  42556. });
  42557. if (this.customShaderNameResolve) {
  42558. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42559. }
  42560. var join = defines.toString();
  42561. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42562. attributes: attribs,
  42563. uniformsNames: uniforms,
  42564. uniformBuffersNames: uniformBuffers,
  42565. samplers: samplers,
  42566. defines: join,
  42567. fallbacks: fallbacks,
  42568. onCompiled: this.onCompiled,
  42569. onError: this.onError,
  42570. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42571. }, engine), defines);
  42572. this.buildUniformLayout();
  42573. }
  42574. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42575. return false;
  42576. }
  42577. defines._renderId = scene.getRenderId();
  42578. this._wasPreviouslyReady = true;
  42579. return true;
  42580. };
  42581. StandardMaterial.prototype.buildUniformLayout = function () {
  42582. // Order is important !
  42583. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42584. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42585. this._uniformBuffer.addUniform("opacityParts", 4);
  42586. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42587. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42588. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42589. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42590. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42591. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42592. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42593. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42594. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42595. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42596. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42597. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42598. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42599. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42600. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42601. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42602. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42603. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42604. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42605. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42606. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42607. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42608. this._uniformBuffer.addUniform("specularMatrix", 16);
  42609. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42610. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42611. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42612. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42613. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42614. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42615. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42616. this._uniformBuffer.addUniform("pointSize", 1);
  42617. this._uniformBuffer.create();
  42618. };
  42619. StandardMaterial.prototype.unbind = function () {
  42620. if (this._activeEffect) {
  42621. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42622. this._activeEffect.setTexture("reflection2DSampler", null);
  42623. }
  42624. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42625. this._activeEffect.setTexture("refraction2DSampler", null);
  42626. }
  42627. }
  42628. _super.prototype.unbind.call(this);
  42629. };
  42630. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42631. var scene = this.getScene();
  42632. var defines = subMesh._materialDefines;
  42633. if (!defines) {
  42634. return;
  42635. }
  42636. var effect = subMesh.effect;
  42637. if (!effect) {
  42638. return;
  42639. }
  42640. this._activeEffect = effect;
  42641. // Matrices
  42642. this.bindOnlyWorldMatrix(world);
  42643. // Normal Matrix
  42644. if (defines.OBJECTSPACE_NORMALMAP) {
  42645. world.toNormalMatrix(this._normalMatrix);
  42646. this.bindOnlyNormalMatrix(this._normalMatrix);
  42647. }
  42648. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42649. // Bones
  42650. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42651. if (mustRebind) {
  42652. this._uniformBuffer.bindToEffect(effect, "Material");
  42653. this.bindViewProjection(effect);
  42654. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42655. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42656. // Fresnel
  42657. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42658. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42659. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42660. }
  42661. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42662. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42663. }
  42664. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42665. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42666. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42667. }
  42668. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42669. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42670. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42671. }
  42672. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42673. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42674. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42675. }
  42676. }
  42677. // Textures
  42678. if (scene.texturesEnabled) {
  42679. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42680. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42681. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42682. }
  42683. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42684. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42685. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42686. }
  42687. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42688. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42689. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42690. }
  42691. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42692. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42693. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42694. if (this._reflectionTexture.boundingBoxSize) {
  42695. var cubeTexture = this._reflectionTexture;
  42696. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42697. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42698. }
  42699. }
  42700. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42701. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42702. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42703. }
  42704. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42705. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42706. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42707. }
  42708. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42709. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42710. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42711. }
  42712. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42713. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42714. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42715. if (scene._mirroredCameraPosition) {
  42716. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42717. }
  42718. else {
  42719. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42720. }
  42721. }
  42722. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42723. var depth = 1.0;
  42724. if (!this._refractionTexture.isCube) {
  42725. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42726. if (this._refractionTexture.depth) {
  42727. depth = this._refractionTexture.depth;
  42728. }
  42729. }
  42730. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42731. }
  42732. }
  42733. // Point size
  42734. if (this.pointsCloud) {
  42735. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42736. }
  42737. if (defines.SPECULARTERM) {
  42738. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42739. }
  42740. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42741. // Diffuse
  42742. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42743. }
  42744. // Textures
  42745. if (scene.texturesEnabled) {
  42746. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42747. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42748. }
  42749. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42750. effect.setTexture("ambientSampler", this._ambientTexture);
  42751. }
  42752. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42753. effect.setTexture("opacitySampler", this._opacityTexture);
  42754. }
  42755. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42756. if (this._reflectionTexture.isCube) {
  42757. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42758. }
  42759. else {
  42760. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42761. }
  42762. }
  42763. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42764. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42765. }
  42766. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42767. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42768. }
  42769. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42770. effect.setTexture("specularSampler", this._specularTexture);
  42771. }
  42772. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42773. effect.setTexture("bumpSampler", this._bumpTexture);
  42774. }
  42775. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42776. var depth = 1.0;
  42777. if (this._refractionTexture.isCube) {
  42778. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42779. }
  42780. else {
  42781. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42782. }
  42783. }
  42784. }
  42785. // Clip plane
  42786. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42787. // Colors
  42788. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42789. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42790. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42791. }
  42792. if (mustRebind || !this.isFrozen) {
  42793. // Lights
  42794. if (scene.lightsEnabled && !this._disableLighting) {
  42795. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42796. }
  42797. // View
  42798. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42799. this.bindView(effect);
  42800. }
  42801. // Fog
  42802. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42803. // Morph targets
  42804. if (defines.NUM_MORPH_INFLUENCERS) {
  42805. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42806. }
  42807. // Log. depth
  42808. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42809. // image processing
  42810. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  42811. this._imageProcessingConfiguration.bind(this._activeEffect);
  42812. }
  42813. }
  42814. this._uniformBuffer.update();
  42815. this._afterBind(mesh, this._activeEffect);
  42816. };
  42817. StandardMaterial.prototype.getAnimatables = function () {
  42818. var results = [];
  42819. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42820. results.push(this._diffuseTexture);
  42821. }
  42822. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42823. results.push(this._ambientTexture);
  42824. }
  42825. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42826. results.push(this._opacityTexture);
  42827. }
  42828. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42829. results.push(this._reflectionTexture);
  42830. }
  42831. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42832. results.push(this._emissiveTexture);
  42833. }
  42834. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42835. results.push(this._specularTexture);
  42836. }
  42837. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42838. results.push(this._bumpTexture);
  42839. }
  42840. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42841. results.push(this._lightmapTexture);
  42842. }
  42843. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42844. results.push(this._refractionTexture);
  42845. }
  42846. return results;
  42847. };
  42848. StandardMaterial.prototype.getActiveTextures = function () {
  42849. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42850. if (this._diffuseTexture) {
  42851. activeTextures.push(this._diffuseTexture);
  42852. }
  42853. if (this._ambientTexture) {
  42854. activeTextures.push(this._ambientTexture);
  42855. }
  42856. if (this._opacityTexture) {
  42857. activeTextures.push(this._opacityTexture);
  42858. }
  42859. if (this._reflectionTexture) {
  42860. activeTextures.push(this._reflectionTexture);
  42861. }
  42862. if (this._emissiveTexture) {
  42863. activeTextures.push(this._emissiveTexture);
  42864. }
  42865. if (this._specularTexture) {
  42866. activeTextures.push(this._specularTexture);
  42867. }
  42868. if (this._bumpTexture) {
  42869. activeTextures.push(this._bumpTexture);
  42870. }
  42871. if (this._lightmapTexture) {
  42872. activeTextures.push(this._lightmapTexture);
  42873. }
  42874. if (this._refractionTexture) {
  42875. activeTextures.push(this._refractionTexture);
  42876. }
  42877. return activeTextures;
  42878. };
  42879. StandardMaterial.prototype.hasTexture = function (texture) {
  42880. if (_super.prototype.hasTexture.call(this, texture)) {
  42881. return true;
  42882. }
  42883. if (this._diffuseTexture === texture) {
  42884. return true;
  42885. }
  42886. if (this._ambientTexture === texture) {
  42887. return true;
  42888. }
  42889. if (this._opacityTexture === texture) {
  42890. return true;
  42891. }
  42892. if (this._reflectionTexture === texture) {
  42893. return true;
  42894. }
  42895. if (this._emissiveTexture === texture) {
  42896. return true;
  42897. }
  42898. if (this._specularTexture === texture) {
  42899. return true;
  42900. }
  42901. if (this._bumpTexture === texture) {
  42902. return true;
  42903. }
  42904. if (this._lightmapTexture === texture) {
  42905. return true;
  42906. }
  42907. if (this._refractionTexture === texture) {
  42908. return true;
  42909. }
  42910. return false;
  42911. };
  42912. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42913. if (forceDisposeTextures) {
  42914. if (this._diffuseTexture) {
  42915. this._diffuseTexture.dispose();
  42916. }
  42917. if (this._ambientTexture) {
  42918. this._ambientTexture.dispose();
  42919. }
  42920. if (this._opacityTexture) {
  42921. this._opacityTexture.dispose();
  42922. }
  42923. if (this._reflectionTexture) {
  42924. this._reflectionTexture.dispose();
  42925. }
  42926. if (this._emissiveTexture) {
  42927. this._emissiveTexture.dispose();
  42928. }
  42929. if (this._specularTexture) {
  42930. this._specularTexture.dispose();
  42931. }
  42932. if (this._bumpTexture) {
  42933. this._bumpTexture.dispose();
  42934. }
  42935. if (this._lightmapTexture) {
  42936. this._lightmapTexture.dispose();
  42937. }
  42938. if (this._refractionTexture) {
  42939. this._refractionTexture.dispose();
  42940. }
  42941. }
  42942. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42943. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42944. }
  42945. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42946. };
  42947. StandardMaterial.prototype.clone = function (name) {
  42948. var _this = this;
  42949. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42950. result.name = name;
  42951. result.id = name;
  42952. return result;
  42953. };
  42954. StandardMaterial.prototype.serialize = function () {
  42955. return BABYLON.SerializationHelper.Serialize(this);
  42956. };
  42957. // Statics
  42958. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42959. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42960. };
  42961. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42962. get: function () {
  42963. return StandardMaterial._DiffuseTextureEnabled;
  42964. },
  42965. set: function (value) {
  42966. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42967. return;
  42968. }
  42969. StandardMaterial._DiffuseTextureEnabled = value;
  42970. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42971. },
  42972. enumerable: true,
  42973. configurable: true
  42974. });
  42975. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42976. get: function () {
  42977. return StandardMaterial._AmbientTextureEnabled;
  42978. },
  42979. set: function (value) {
  42980. if (StandardMaterial._AmbientTextureEnabled === value) {
  42981. return;
  42982. }
  42983. StandardMaterial._AmbientTextureEnabled = value;
  42984. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42985. },
  42986. enumerable: true,
  42987. configurable: true
  42988. });
  42989. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42990. get: function () {
  42991. return StandardMaterial._OpacityTextureEnabled;
  42992. },
  42993. set: function (value) {
  42994. if (StandardMaterial._OpacityTextureEnabled === value) {
  42995. return;
  42996. }
  42997. StandardMaterial._OpacityTextureEnabled = value;
  42998. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42999. },
  43000. enumerable: true,
  43001. configurable: true
  43002. });
  43003. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43004. get: function () {
  43005. return StandardMaterial._ReflectionTextureEnabled;
  43006. },
  43007. set: function (value) {
  43008. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43009. return;
  43010. }
  43011. StandardMaterial._ReflectionTextureEnabled = value;
  43012. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43013. },
  43014. enumerable: true,
  43015. configurable: true
  43016. });
  43017. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43018. get: function () {
  43019. return StandardMaterial._EmissiveTextureEnabled;
  43020. },
  43021. set: function (value) {
  43022. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43023. return;
  43024. }
  43025. StandardMaterial._EmissiveTextureEnabled = value;
  43026. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43027. },
  43028. enumerable: true,
  43029. configurable: true
  43030. });
  43031. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43032. get: function () {
  43033. return StandardMaterial._SpecularTextureEnabled;
  43034. },
  43035. set: function (value) {
  43036. if (StandardMaterial._SpecularTextureEnabled === value) {
  43037. return;
  43038. }
  43039. StandardMaterial._SpecularTextureEnabled = value;
  43040. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43041. },
  43042. enumerable: true,
  43043. configurable: true
  43044. });
  43045. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43046. get: function () {
  43047. return StandardMaterial._BumpTextureEnabled;
  43048. },
  43049. set: function (value) {
  43050. if (StandardMaterial._BumpTextureEnabled === value) {
  43051. return;
  43052. }
  43053. StandardMaterial._BumpTextureEnabled = value;
  43054. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43055. },
  43056. enumerable: true,
  43057. configurable: true
  43058. });
  43059. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43060. get: function () {
  43061. return StandardMaterial._LightmapTextureEnabled;
  43062. },
  43063. set: function (value) {
  43064. if (StandardMaterial._LightmapTextureEnabled === value) {
  43065. return;
  43066. }
  43067. StandardMaterial._LightmapTextureEnabled = value;
  43068. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43069. },
  43070. enumerable: true,
  43071. configurable: true
  43072. });
  43073. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43074. get: function () {
  43075. return StandardMaterial._RefractionTextureEnabled;
  43076. },
  43077. set: function (value) {
  43078. if (StandardMaterial._RefractionTextureEnabled === value) {
  43079. return;
  43080. }
  43081. StandardMaterial._RefractionTextureEnabled = value;
  43082. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43083. },
  43084. enumerable: true,
  43085. configurable: true
  43086. });
  43087. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43088. get: function () {
  43089. return StandardMaterial._ColorGradingTextureEnabled;
  43090. },
  43091. set: function (value) {
  43092. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43093. return;
  43094. }
  43095. StandardMaterial._ColorGradingTextureEnabled = value;
  43096. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43097. },
  43098. enumerable: true,
  43099. configurable: true
  43100. });
  43101. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43102. get: function () {
  43103. return StandardMaterial._FresnelEnabled;
  43104. },
  43105. set: function (value) {
  43106. if (StandardMaterial._FresnelEnabled === value) {
  43107. return;
  43108. }
  43109. StandardMaterial._FresnelEnabled = value;
  43110. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43111. },
  43112. enumerable: true,
  43113. configurable: true
  43114. });
  43115. // Flags used to enable or disable a type of texture for all Standard Materials
  43116. StandardMaterial._DiffuseTextureEnabled = true;
  43117. StandardMaterial._AmbientTextureEnabled = true;
  43118. StandardMaterial._OpacityTextureEnabled = true;
  43119. StandardMaterial._ReflectionTextureEnabled = true;
  43120. StandardMaterial._EmissiveTextureEnabled = true;
  43121. StandardMaterial._SpecularTextureEnabled = true;
  43122. StandardMaterial._BumpTextureEnabled = true;
  43123. StandardMaterial._LightmapTextureEnabled = true;
  43124. StandardMaterial._RefractionTextureEnabled = true;
  43125. StandardMaterial._ColorGradingTextureEnabled = true;
  43126. StandardMaterial._FresnelEnabled = true;
  43127. __decorate([
  43128. BABYLON.serializeAsTexture("diffuseTexture")
  43129. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43130. __decorate([
  43131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43132. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43133. __decorate([
  43134. BABYLON.serializeAsTexture("ambientTexture")
  43135. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43136. __decorate([
  43137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43138. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43139. __decorate([
  43140. BABYLON.serializeAsTexture("opacityTexture")
  43141. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43142. __decorate([
  43143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43144. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43145. __decorate([
  43146. BABYLON.serializeAsTexture("reflectionTexture")
  43147. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43148. __decorate([
  43149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43150. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43151. __decorate([
  43152. BABYLON.serializeAsTexture("emissiveTexture")
  43153. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43154. __decorate([
  43155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43156. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43157. __decorate([
  43158. BABYLON.serializeAsTexture("specularTexture")
  43159. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43160. __decorate([
  43161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43162. ], StandardMaterial.prototype, "specularTexture", void 0);
  43163. __decorate([
  43164. BABYLON.serializeAsTexture("bumpTexture")
  43165. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43166. __decorate([
  43167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43168. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43169. __decorate([
  43170. BABYLON.serializeAsTexture("lightmapTexture")
  43171. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43172. __decorate([
  43173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43174. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43175. __decorate([
  43176. BABYLON.serializeAsTexture("refractionTexture")
  43177. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43178. __decorate([
  43179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43180. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43181. __decorate([
  43182. BABYLON.serializeAsColor3("ambient")
  43183. ], StandardMaterial.prototype, "ambientColor", void 0);
  43184. __decorate([
  43185. BABYLON.serializeAsColor3("diffuse")
  43186. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43187. __decorate([
  43188. BABYLON.serializeAsColor3("specular")
  43189. ], StandardMaterial.prototype, "specularColor", void 0);
  43190. __decorate([
  43191. BABYLON.serializeAsColor3("emissive")
  43192. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43193. __decorate([
  43194. BABYLON.serialize()
  43195. ], StandardMaterial.prototype, "specularPower", void 0);
  43196. __decorate([
  43197. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43198. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43199. __decorate([
  43200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43201. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43202. __decorate([
  43203. BABYLON.serialize("useEmissiveAsIllumination")
  43204. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43205. __decorate([
  43206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43207. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43208. __decorate([
  43209. BABYLON.serialize("linkEmissiveWithDiffuse")
  43210. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43211. __decorate([
  43212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43213. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43214. __decorate([
  43215. BABYLON.serialize("useSpecularOverAlpha")
  43216. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43217. __decorate([
  43218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43219. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43220. __decorate([
  43221. BABYLON.serialize("useReflectionOverAlpha")
  43222. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43223. __decorate([
  43224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43225. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43226. __decorate([
  43227. BABYLON.serialize("disableLighting")
  43228. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43229. __decorate([
  43230. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43231. ], StandardMaterial.prototype, "disableLighting", void 0);
  43232. __decorate([
  43233. BABYLON.serialize("useObjectSpaceNormalMap")
  43234. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43235. __decorate([
  43236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43237. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43238. __decorate([
  43239. BABYLON.serialize("useParallax")
  43240. ], StandardMaterial.prototype, "_useParallax", void 0);
  43241. __decorate([
  43242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43243. ], StandardMaterial.prototype, "useParallax", void 0);
  43244. __decorate([
  43245. BABYLON.serialize("useParallaxOcclusion")
  43246. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43247. __decorate([
  43248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43249. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43250. __decorate([
  43251. BABYLON.serialize()
  43252. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43253. __decorate([
  43254. BABYLON.serialize("roughness")
  43255. ], StandardMaterial.prototype, "_roughness", void 0);
  43256. __decorate([
  43257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43258. ], StandardMaterial.prototype, "roughness", void 0);
  43259. __decorate([
  43260. BABYLON.serialize()
  43261. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43262. __decorate([
  43263. BABYLON.serialize()
  43264. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43265. __decorate([
  43266. BABYLON.serialize("useLightmapAsShadowmap")
  43267. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43268. __decorate([
  43269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43270. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43271. __decorate([
  43272. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43273. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43274. __decorate([
  43275. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43276. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43277. __decorate([
  43278. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43279. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43280. __decorate([
  43281. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43282. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43283. __decorate([
  43284. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43285. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43286. __decorate([
  43287. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43288. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43289. __decorate([
  43290. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43291. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43292. __decorate([
  43293. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43294. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43295. __decorate([
  43296. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43297. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43298. __decorate([
  43299. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43300. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43301. __decorate([
  43302. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43303. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43304. __decorate([
  43305. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43306. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43307. __decorate([
  43308. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43309. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43310. __decorate([
  43311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43312. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43313. __decorate([
  43314. BABYLON.serialize("maxSimultaneousLights")
  43315. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43316. __decorate([
  43317. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43318. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43319. __decorate([
  43320. BABYLON.serialize("invertNormalMapX")
  43321. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43322. __decorate([
  43323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43324. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43325. __decorate([
  43326. BABYLON.serialize("invertNormalMapY")
  43327. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43328. __decorate([
  43329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43330. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43331. __decorate([
  43332. BABYLON.serialize("twoSidedLighting")
  43333. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43334. __decorate([
  43335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43336. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43337. __decorate([
  43338. BABYLON.serialize()
  43339. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43340. return StandardMaterial;
  43341. }(BABYLON.PushMaterial));
  43342. BABYLON.StandardMaterial = StandardMaterial;
  43343. })(BABYLON || (BABYLON = {}));
  43344. //# sourceMappingURL=babylon.standardMaterial.js.map
  43345. "use strict";
  43346. var BABYLON;
  43347. (function (BABYLON) {
  43348. /**
  43349. * Manages the defines for the PBR Material.
  43350. * @ignoreChildren
  43351. */
  43352. var PBRMaterialDefines = /** @class */ (function (_super) {
  43353. __extends(PBRMaterialDefines, _super);
  43354. /**
  43355. * Initializes the PBR Material defines.
  43356. */
  43357. function PBRMaterialDefines() {
  43358. var _this = _super.call(this) || this;
  43359. _this.PBR = true;
  43360. _this.MAINUV1 = false;
  43361. _this.MAINUV2 = false;
  43362. _this.UV1 = false;
  43363. _this.UV2 = false;
  43364. _this.ALBEDO = false;
  43365. _this.ALBEDODIRECTUV = 0;
  43366. _this.VERTEXCOLOR = false;
  43367. _this.AMBIENT = false;
  43368. _this.AMBIENTDIRECTUV = 0;
  43369. _this.AMBIENTINGRAYSCALE = false;
  43370. _this.OPACITY = false;
  43371. _this.VERTEXALPHA = false;
  43372. _this.OPACITYDIRECTUV = 0;
  43373. _this.OPACITYRGB = false;
  43374. _this.ALPHATEST = false;
  43375. _this.DEPTHPREPASS = false;
  43376. _this.ALPHABLEND = false;
  43377. _this.ALPHAFROMALBEDO = false;
  43378. _this.ALPHATESTVALUE = "0.5";
  43379. _this.SPECULAROVERALPHA = false;
  43380. _this.RADIANCEOVERALPHA = false;
  43381. _this.ALPHAFRESNEL = false;
  43382. _this.LINEARALPHAFRESNEL = false;
  43383. _this.PREMULTIPLYALPHA = false;
  43384. _this.EMISSIVE = false;
  43385. _this.EMISSIVEDIRECTUV = 0;
  43386. _this.REFLECTIVITY = false;
  43387. _this.REFLECTIVITYDIRECTUV = 0;
  43388. _this.SPECULARTERM = false;
  43389. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43390. _this.MICROSURFACEAUTOMATIC = false;
  43391. _this.LODBASEDMICROSFURACE = false;
  43392. _this.MICROSURFACEMAP = false;
  43393. _this.MICROSURFACEMAPDIRECTUV = 0;
  43394. _this.METALLICWORKFLOW = false;
  43395. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43396. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43397. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43398. _this.AOSTOREINMETALMAPRED = false;
  43399. _this.ENVIRONMENTBRDF = false;
  43400. _this.NORMAL = false;
  43401. _this.TANGENT = false;
  43402. _this.BUMP = false;
  43403. _this.BUMPDIRECTUV = 0;
  43404. _this.OBJECTSPACE_NORMALMAP = false;
  43405. _this.PARALLAX = false;
  43406. _this.PARALLAXOCCLUSION = false;
  43407. _this.NORMALXYSCALE = true;
  43408. _this.LIGHTMAP = false;
  43409. _this.LIGHTMAPDIRECTUV = 0;
  43410. _this.USELIGHTMAPASSHADOWMAP = false;
  43411. _this.GAMMALIGHTMAP = false;
  43412. _this.REFLECTION = false;
  43413. _this.REFLECTIONMAP_3D = false;
  43414. _this.REFLECTIONMAP_SPHERICAL = false;
  43415. _this.REFLECTIONMAP_PLANAR = false;
  43416. _this.REFLECTIONMAP_CUBIC = false;
  43417. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43418. _this.REFLECTIONMAP_PROJECTION = false;
  43419. _this.REFLECTIONMAP_SKYBOX = false;
  43420. _this.REFLECTIONMAP_EXPLICIT = false;
  43421. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43422. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43423. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43424. _this.INVERTCUBICMAP = false;
  43425. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43426. _this.USESPHERICALINVERTEX = false;
  43427. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43428. _this.LODINREFLECTIONALPHA = false;
  43429. _this.GAMMAREFLECTION = false;
  43430. _this.RADIANCEOCCLUSION = false;
  43431. _this.HORIZONOCCLUSION = false;
  43432. _this.REFRACTION = false;
  43433. _this.REFRACTIONMAP_3D = false;
  43434. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43435. _this.LODINREFRACTIONALPHA = false;
  43436. _this.GAMMAREFRACTION = false;
  43437. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43438. _this.INSTANCES = false;
  43439. _this.NUM_BONE_INFLUENCERS = 0;
  43440. _this.BonesPerMesh = 0;
  43441. _this.NONUNIFORMSCALING = false;
  43442. _this.MORPHTARGETS = false;
  43443. _this.MORPHTARGETS_NORMAL = false;
  43444. _this.MORPHTARGETS_TANGENT = false;
  43445. _this.NUM_MORPH_INFLUENCERS = 0;
  43446. _this.IMAGEPROCESSING = false;
  43447. _this.VIGNETTE = false;
  43448. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43449. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43450. _this.TONEMAPPING = false;
  43451. _this.CONTRAST = false;
  43452. _this.COLORCURVES = false;
  43453. _this.COLORGRADING = false;
  43454. _this.COLORGRADING3D = false;
  43455. _this.SAMPLER3DGREENDEPTH = false;
  43456. _this.SAMPLER3DBGRMAP = false;
  43457. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43458. _this.EXPOSURE = false;
  43459. _this.USEPHYSICALLIGHTFALLOFF = false;
  43460. _this.TWOSIDEDLIGHTING = false;
  43461. _this.SHADOWFLOAT = false;
  43462. _this.CLIPPLANE = false;
  43463. _this.POINTSIZE = false;
  43464. _this.FOG = false;
  43465. _this.LOGARITHMICDEPTH = false;
  43466. _this.FORCENORMALFORWARD = false;
  43467. _this.GEOMETRYAA = false;
  43468. _this.UNLIT = false;
  43469. _this.rebuild();
  43470. return _this;
  43471. }
  43472. /**
  43473. * Resets the PBR Material defines.
  43474. */
  43475. PBRMaterialDefines.prototype.reset = function () {
  43476. _super.prototype.reset.call(this);
  43477. this.ALPHATESTVALUE = "0.5";
  43478. this.PBR = true;
  43479. };
  43480. return PBRMaterialDefines;
  43481. }(BABYLON.MaterialDefines));
  43482. /**
  43483. * The Physically based material base class of BJS.
  43484. *
  43485. * This offers the main features of a standard PBR material.
  43486. * For more information, please refer to the documentation :
  43487. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43488. */
  43489. var PBRBaseMaterial = /** @class */ (function (_super) {
  43490. __extends(PBRBaseMaterial, _super);
  43491. /**
  43492. * Instantiates a new PBRMaterial instance.
  43493. *
  43494. * @param name The material name
  43495. * @param scene The scene the material will be use in.
  43496. */
  43497. function PBRBaseMaterial(name, scene) {
  43498. var _this = _super.call(this, name, scene) || this;
  43499. /**
  43500. * Intensity of the direct lights e.g. the four lights available in your scene.
  43501. * This impacts both the direct diffuse and specular highlights.
  43502. */
  43503. _this._directIntensity = 1.0;
  43504. /**
  43505. * Intensity of the emissive part of the material.
  43506. * This helps controlling the emissive effect without modifying the emissive color.
  43507. */
  43508. _this._emissiveIntensity = 1.0;
  43509. /**
  43510. * Intensity of the environment e.g. how much the environment will light the object
  43511. * either through harmonics for rough material or through the refelction for shiny ones.
  43512. */
  43513. _this._environmentIntensity = 1.0;
  43514. /**
  43515. * This is a special control allowing the reduction of the specular highlights coming from the
  43516. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43517. */
  43518. _this._specularIntensity = 1.0;
  43519. /**
  43520. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43521. */
  43522. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43523. /**
  43524. * Debug Control allowing disabling the bump map on this material.
  43525. */
  43526. _this._disableBumpMap = false;
  43527. /**
  43528. * AKA Occlusion Texture Intensity in other nomenclature.
  43529. */
  43530. _this._ambientTextureStrength = 1.0;
  43531. /**
  43532. * The color of a material in ambient lighting.
  43533. */
  43534. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43535. /**
  43536. * AKA Diffuse Color in other nomenclature.
  43537. */
  43538. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43539. /**
  43540. * AKA Specular Color in other nomenclature.
  43541. */
  43542. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43543. /**
  43544. * The color applied when light is reflected from a material.
  43545. */
  43546. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43547. /**
  43548. * The color applied when light is emitted from a material.
  43549. */
  43550. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43551. /**
  43552. * AKA Glossiness in other nomenclature.
  43553. */
  43554. _this._microSurface = 0.9;
  43555. /**
  43556. * source material index of refraction (IOR)' / 'destination material IOR.
  43557. */
  43558. _this._indexOfRefraction = 0.66;
  43559. /**
  43560. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43561. */
  43562. _this._invertRefractionY = false;
  43563. /**
  43564. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43565. * Materials half opaque for instance using refraction could benefit from this control.
  43566. */
  43567. _this._linkRefractionWithTransparency = false;
  43568. /**
  43569. * Specifies that the material will use the light map as a show map.
  43570. */
  43571. _this._useLightmapAsShadowmap = false;
  43572. /**
  43573. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43574. * makes the reflect vector face the model (under horizon).
  43575. */
  43576. _this._useHorizonOcclusion = true;
  43577. /**
  43578. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43579. * too much the area relying on ambient texture to define their ambient occlusion.
  43580. */
  43581. _this._useRadianceOcclusion = true;
  43582. /**
  43583. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43584. */
  43585. _this._useAlphaFromAlbedoTexture = false;
  43586. /**
  43587. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43588. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43589. */
  43590. _this._useSpecularOverAlpha = true;
  43591. /**
  43592. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43593. */
  43594. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43595. /**
  43596. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43597. */
  43598. _this._useRoughnessFromMetallicTextureAlpha = true;
  43599. /**
  43600. * Specifies if the metallic texture contains the roughness information in its green channel.
  43601. */
  43602. _this._useRoughnessFromMetallicTextureGreen = false;
  43603. /**
  43604. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43605. */
  43606. _this._useMetallnessFromMetallicTextureBlue = false;
  43607. /**
  43608. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43609. */
  43610. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43611. /**
  43612. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43613. */
  43614. _this._useAmbientInGrayScale = false;
  43615. /**
  43616. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43617. * The material will try to infer what glossiness each pixel should be.
  43618. */
  43619. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43620. /**
  43621. * BJS is using an harcoded light falloff based on a manually sets up range.
  43622. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43623. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43624. */
  43625. _this._usePhysicalLightFalloff = true;
  43626. /**
  43627. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43628. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43629. */
  43630. _this._useRadianceOverAlpha = true;
  43631. /**
  43632. * Allows using an object space normal map (instead of tangent space).
  43633. */
  43634. _this._useObjectSpaceNormalMap = false;
  43635. /**
  43636. * Allows using the bump map in parallax mode.
  43637. */
  43638. _this._useParallax = false;
  43639. /**
  43640. * Allows using the bump map in parallax occlusion mode.
  43641. */
  43642. _this._useParallaxOcclusion = false;
  43643. /**
  43644. * Controls the scale bias of the parallax mode.
  43645. */
  43646. _this._parallaxScaleBias = 0.05;
  43647. /**
  43648. * If sets to true, disables all the lights affecting the material.
  43649. */
  43650. _this._disableLighting = false;
  43651. /**
  43652. * Number of Simultaneous lights allowed on the material.
  43653. */
  43654. _this._maxSimultaneousLights = 4;
  43655. /**
  43656. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43657. */
  43658. _this._invertNormalMapX = false;
  43659. /**
  43660. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43661. */
  43662. _this._invertNormalMapY = false;
  43663. /**
  43664. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43665. */
  43666. _this._twoSidedLighting = false;
  43667. /**
  43668. * Defines the alpha limits in alpha test mode.
  43669. */
  43670. _this._alphaCutOff = 0.4;
  43671. /**
  43672. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43673. */
  43674. _this._forceAlphaTest = false;
  43675. /**
  43676. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43677. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43678. */
  43679. _this._useAlphaFresnel = false;
  43680. /**
  43681. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43682. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43683. */
  43684. _this._useLinearAlphaFresnel = false;
  43685. /**
  43686. * The transparency mode of the material.
  43687. */
  43688. _this._transparencyMode = null;
  43689. /**
  43690. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43691. * from cos thetav and roughness:
  43692. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43693. */
  43694. _this._environmentBRDFTexture = null;
  43695. /**
  43696. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43697. */
  43698. _this._forceIrradianceInFragment = false;
  43699. /**
  43700. * Force normal to face away from face.
  43701. */
  43702. _this._forceNormalForward = false;
  43703. /**
  43704. * Enables specular anti aliasing in the PBR shader.
  43705. * It will both interacts on the Geometry for analytical and IBL lighting.
  43706. * It also prefilter the roughness map based on the bump values.
  43707. */
  43708. _this._enableSpecularAntiAliasing = false;
  43709. /**
  43710. * Stores the available render targets.
  43711. */
  43712. _this._renderTargets = new BABYLON.SmartArray(16);
  43713. /**
  43714. * Sets the global ambient color for the material used in lighting calculations.
  43715. */
  43716. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43717. /**
  43718. * If set to true, no lighting calculations will be applied.
  43719. */
  43720. _this._unlit = false;
  43721. // Setup the default processing configuration to the scene.
  43722. _this._attachImageProcessingConfiguration(null);
  43723. _this.getRenderTargetTextures = function () {
  43724. _this._renderTargets.reset();
  43725. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43726. _this._renderTargets.push(_this._reflectionTexture);
  43727. }
  43728. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43729. _this._renderTargets.push(_this._refractionTexture);
  43730. }
  43731. return _this._renderTargets;
  43732. };
  43733. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43734. return _this;
  43735. }
  43736. /**
  43737. * Attaches a new image processing configuration to the PBR Material.
  43738. * @param configuration
  43739. */
  43740. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43741. var _this = this;
  43742. if (configuration === this._imageProcessingConfiguration) {
  43743. return;
  43744. }
  43745. // Detaches observer.
  43746. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43747. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43748. }
  43749. // Pick the scene configuration if needed.
  43750. if (!configuration) {
  43751. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43752. }
  43753. else {
  43754. this._imageProcessingConfiguration = configuration;
  43755. }
  43756. // Attaches observer.
  43757. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43758. _this._markAllSubMeshesAsImageProcessingDirty();
  43759. });
  43760. };
  43761. /**
  43762. * Gets the name of the material class.
  43763. */
  43764. PBRBaseMaterial.prototype.getClassName = function () {
  43765. return "PBRBaseMaterial";
  43766. };
  43767. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43768. /**
  43769. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43770. */
  43771. get: function () {
  43772. return this._useLogarithmicDepth;
  43773. },
  43774. /**
  43775. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43776. */
  43777. set: function (value) {
  43778. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43779. },
  43780. enumerable: true,
  43781. configurable: true
  43782. });
  43783. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43784. /**
  43785. * Gets the current transparency mode.
  43786. */
  43787. get: function () {
  43788. return this._transparencyMode;
  43789. },
  43790. /**
  43791. * Sets the transparency mode of the material.
  43792. */
  43793. set: function (value) {
  43794. if (this._transparencyMode === value) {
  43795. return;
  43796. }
  43797. this._transparencyMode = value;
  43798. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43799. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43800. },
  43801. enumerable: true,
  43802. configurable: true
  43803. });
  43804. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43805. /**
  43806. * Returns true if alpha blending should be disabled.
  43807. */
  43808. get: function () {
  43809. return (this._linkRefractionWithTransparency ||
  43810. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43811. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43812. },
  43813. enumerable: true,
  43814. configurable: true
  43815. });
  43816. /**
  43817. * Specifies whether or not this material should be rendered in alpha blend mode.
  43818. */
  43819. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43820. if (this._disableAlphaBlending) {
  43821. return false;
  43822. }
  43823. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43824. };
  43825. /**
  43826. * Specifies if the mesh will require alpha blending.
  43827. * @param mesh - BJS mesh.
  43828. */
  43829. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43830. if (this._disableAlphaBlending) {
  43831. return false;
  43832. }
  43833. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43834. };
  43835. /**
  43836. * Specifies whether or not this material should be rendered in alpha test mode.
  43837. */
  43838. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43839. if (this._forceAlphaTest) {
  43840. return true;
  43841. }
  43842. if (this._linkRefractionWithTransparency) {
  43843. return false;
  43844. }
  43845. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43846. };
  43847. /**
  43848. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43849. */
  43850. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43851. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43852. };
  43853. /**
  43854. * Gets the texture used for the alpha test.
  43855. */
  43856. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43857. return this._albedoTexture;
  43858. };
  43859. /**
  43860. * Specifies that the submesh is ready to be used.
  43861. * @param mesh - BJS mesh.
  43862. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43863. * @param useInstances - Specifies that instances should be used.
  43864. * @returns - boolean indicating that the submesh is ready or not.
  43865. */
  43866. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43867. if (subMesh.effect && this.isFrozen) {
  43868. if (this._wasPreviouslyReady) {
  43869. return true;
  43870. }
  43871. }
  43872. if (!subMesh._materialDefines) {
  43873. subMesh._materialDefines = new PBRMaterialDefines();
  43874. }
  43875. var defines = subMesh._materialDefines;
  43876. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43877. if (defines._renderId === this.getScene().getRenderId()) {
  43878. return true;
  43879. }
  43880. }
  43881. var scene = this.getScene();
  43882. var engine = scene.getEngine();
  43883. if (defines._areTexturesDirty) {
  43884. if (scene.texturesEnabled) {
  43885. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43886. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43887. return false;
  43888. }
  43889. }
  43890. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43891. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43892. return false;
  43893. }
  43894. }
  43895. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43896. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43897. return false;
  43898. }
  43899. }
  43900. var reflectionTexture = this._getReflectionTexture();
  43901. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43902. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43903. return false;
  43904. }
  43905. }
  43906. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43907. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43908. return false;
  43909. }
  43910. }
  43911. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43912. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43913. return false;
  43914. }
  43915. }
  43916. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43917. if (this._metallicTexture) {
  43918. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43919. return false;
  43920. }
  43921. }
  43922. else if (this._reflectivityTexture) {
  43923. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43924. return false;
  43925. }
  43926. }
  43927. if (this._microSurfaceTexture) {
  43928. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43929. return false;
  43930. }
  43931. }
  43932. }
  43933. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43934. // Bump texture cannot be not blocking.
  43935. if (!this._bumpTexture.isReady()) {
  43936. return false;
  43937. }
  43938. }
  43939. var refractionTexture = this._getRefractionTexture();
  43940. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43941. if (!refractionTexture.isReadyOrNotBlocking()) {
  43942. return false;
  43943. }
  43944. }
  43945. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43946. // This is blocking.
  43947. if (!this._environmentBRDFTexture.isReady()) {
  43948. return false;
  43949. }
  43950. }
  43951. }
  43952. }
  43953. if (defines._areImageProcessingDirty) {
  43954. if (!this._imageProcessingConfiguration.isReady()) {
  43955. return false;
  43956. }
  43957. }
  43958. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43959. mesh.createNormals(true);
  43960. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43961. }
  43962. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43963. if (effect) {
  43964. scene.resetCachedMaterial();
  43965. subMesh.setEffect(effect, defines);
  43966. this.buildUniformLayout();
  43967. }
  43968. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43969. return false;
  43970. }
  43971. defines._renderId = scene.getRenderId();
  43972. this._wasPreviouslyReady = true;
  43973. return true;
  43974. };
  43975. /**
  43976. * Specifies if the material uses metallic roughness workflow.
  43977. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43978. */
  43979. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43980. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43981. return true;
  43982. }
  43983. return false;
  43984. };
  43985. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43986. if (onCompiled === void 0) { onCompiled = null; }
  43987. if (onError === void 0) { onError = null; }
  43988. if (useInstances === void 0) { useInstances = null; }
  43989. if (useClipPlane === void 0) { useClipPlane = null; }
  43990. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43991. if (!defines.isDirty) {
  43992. return null;
  43993. }
  43994. defines.markAsProcessed();
  43995. var scene = this.getScene();
  43996. var engine = scene.getEngine();
  43997. // Fallbacks
  43998. var fallbacks = new BABYLON.EffectFallbacks();
  43999. var fallbackRank = 0;
  44000. if (defines.USESPHERICALINVERTEX) {
  44001. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44002. }
  44003. if (defines.FOG) {
  44004. fallbacks.addFallback(fallbackRank, "FOG");
  44005. }
  44006. if (defines.POINTSIZE) {
  44007. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44008. }
  44009. if (defines.LOGARITHMICDEPTH) {
  44010. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44011. }
  44012. if (defines.PARALLAX) {
  44013. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44014. }
  44015. if (defines.PARALLAXOCCLUSION) {
  44016. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44017. }
  44018. if (defines.ENVIRONMENTBRDF) {
  44019. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44020. }
  44021. if (defines.TANGENT) {
  44022. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44023. }
  44024. if (defines.BUMP) {
  44025. fallbacks.addFallback(fallbackRank++, "BUMP");
  44026. }
  44027. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44028. if (defines.SPECULARTERM) {
  44029. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44030. }
  44031. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44032. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44033. }
  44034. if (defines.LIGHTMAP) {
  44035. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44036. }
  44037. if (defines.NORMAL) {
  44038. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44039. }
  44040. if (defines.AMBIENT) {
  44041. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44042. }
  44043. if (defines.EMISSIVE) {
  44044. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44045. }
  44046. if (defines.VERTEXCOLOR) {
  44047. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44048. }
  44049. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44050. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44051. }
  44052. if (defines.MORPHTARGETS) {
  44053. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44054. }
  44055. //Attributes
  44056. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44057. if (defines.NORMAL) {
  44058. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44059. }
  44060. if (defines.TANGENT) {
  44061. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44062. }
  44063. if (defines.UV1) {
  44064. attribs.push(BABYLON.VertexBuffer.UVKind);
  44065. }
  44066. if (defines.UV2) {
  44067. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44068. }
  44069. if (defines.VERTEXCOLOR) {
  44070. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44071. }
  44072. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44073. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44074. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44075. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44076. "vFogInfos", "vFogColor", "pointSize",
  44077. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44078. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44079. "mBones",
  44080. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44081. "vLightingIntensity",
  44082. "logarithmicDepthConstant",
  44083. "vSphericalX", "vSphericalY", "vSphericalZ",
  44084. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44085. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44086. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44087. "vTangentSpaceParams"
  44088. ];
  44089. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44090. "bumpSampler", "lightmapSampler", "opacitySampler",
  44091. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44092. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44093. "microSurfaceSampler", "environmentBrdfSampler"];
  44094. var uniformBuffers = ["Material", "Scene"];
  44095. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44096. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44097. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44098. uniformsNames: uniforms,
  44099. uniformBuffersNames: uniformBuffers,
  44100. samplers: samplers,
  44101. defines: defines,
  44102. maxSimultaneousLights: this._maxSimultaneousLights
  44103. });
  44104. var join = defines.toString();
  44105. return engine.createEffect("pbr", {
  44106. attributes: attribs,
  44107. uniformsNames: uniforms,
  44108. uniformBuffersNames: uniformBuffers,
  44109. samplers: samplers,
  44110. defines: join,
  44111. fallbacks: fallbacks,
  44112. onCompiled: onCompiled,
  44113. onError: onError,
  44114. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44115. }, engine);
  44116. };
  44117. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44118. if (useInstances === void 0) { useInstances = null; }
  44119. if (useClipPlane === void 0) { useClipPlane = null; }
  44120. var scene = this.getScene();
  44121. var engine = scene.getEngine();
  44122. // Lights
  44123. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44124. defines._needNormals = true;
  44125. // Textures
  44126. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44127. if (defines._areTexturesDirty) {
  44128. defines._needUVs = false;
  44129. if (scene.texturesEnabled) {
  44130. if (scene.getEngine().getCaps().textureLOD) {
  44131. defines.LODBASEDMICROSFURACE = true;
  44132. }
  44133. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44134. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44135. }
  44136. else {
  44137. defines.ALBEDO = false;
  44138. }
  44139. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44140. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44141. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44142. }
  44143. else {
  44144. defines.AMBIENT = false;
  44145. }
  44146. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44147. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44148. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44149. }
  44150. else {
  44151. defines.OPACITY = false;
  44152. }
  44153. var reflectionTexture = this._getReflectionTexture();
  44154. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44155. defines.REFLECTION = true;
  44156. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44157. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44158. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44159. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44160. defines.INVERTCUBICMAP = true;
  44161. }
  44162. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44163. switch (reflectionTexture.coordinatesMode) {
  44164. case BABYLON.Texture.CUBIC_MODE:
  44165. case BABYLON.Texture.INVCUBIC_MODE:
  44166. defines.REFLECTIONMAP_CUBIC = true;
  44167. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44168. break;
  44169. case BABYLON.Texture.EXPLICIT_MODE:
  44170. defines.REFLECTIONMAP_EXPLICIT = true;
  44171. break;
  44172. case BABYLON.Texture.PLANAR_MODE:
  44173. defines.REFLECTIONMAP_PLANAR = true;
  44174. break;
  44175. case BABYLON.Texture.PROJECTION_MODE:
  44176. defines.REFLECTIONMAP_PROJECTION = true;
  44177. break;
  44178. case BABYLON.Texture.SKYBOX_MODE:
  44179. defines.REFLECTIONMAP_SKYBOX = true;
  44180. break;
  44181. case BABYLON.Texture.SPHERICAL_MODE:
  44182. defines.REFLECTIONMAP_SPHERICAL = true;
  44183. break;
  44184. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44185. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44186. break;
  44187. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44188. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44189. break;
  44190. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44191. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44192. break;
  44193. }
  44194. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44195. if (reflectionTexture.sphericalPolynomial) {
  44196. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44197. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44198. defines.USESPHERICALINVERTEX = false;
  44199. }
  44200. else {
  44201. defines.USESPHERICALINVERTEX = true;
  44202. }
  44203. }
  44204. }
  44205. }
  44206. else {
  44207. defines.REFLECTION = false;
  44208. defines.REFLECTIONMAP_3D = false;
  44209. defines.REFLECTIONMAP_SPHERICAL = false;
  44210. defines.REFLECTIONMAP_PLANAR = false;
  44211. defines.REFLECTIONMAP_CUBIC = false;
  44212. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44213. defines.REFLECTIONMAP_PROJECTION = false;
  44214. defines.REFLECTIONMAP_SKYBOX = false;
  44215. defines.REFLECTIONMAP_EXPLICIT = false;
  44216. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44217. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44218. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44219. defines.INVERTCUBICMAP = false;
  44220. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44221. defines.USESPHERICALINVERTEX = false;
  44222. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44223. defines.LODINREFLECTIONALPHA = false;
  44224. defines.GAMMAREFLECTION = false;
  44225. }
  44226. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44227. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44228. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44229. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44230. }
  44231. else {
  44232. defines.LIGHTMAP = false;
  44233. }
  44234. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44235. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44236. }
  44237. else {
  44238. defines.EMISSIVE = false;
  44239. }
  44240. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44241. if (this._metallicTexture) {
  44242. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44243. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44244. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44245. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44246. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44247. }
  44248. else if (this._reflectivityTexture) {
  44249. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44250. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44251. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44252. }
  44253. else {
  44254. defines.REFLECTIVITY = false;
  44255. }
  44256. if (this._microSurfaceTexture) {
  44257. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44258. }
  44259. else {
  44260. defines.MICROSURFACEMAP = false;
  44261. }
  44262. }
  44263. else {
  44264. defines.REFLECTIVITY = false;
  44265. defines.MICROSURFACEMAP = false;
  44266. }
  44267. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44268. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44269. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44270. defines.PARALLAX = true;
  44271. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44272. }
  44273. else {
  44274. defines.PARALLAX = false;
  44275. }
  44276. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44277. }
  44278. else {
  44279. defines.BUMP = false;
  44280. }
  44281. var refractionTexture = this._getRefractionTexture();
  44282. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44283. defines.REFRACTION = true;
  44284. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44285. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44286. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44287. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44288. if (this._linkRefractionWithTransparency) {
  44289. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44290. }
  44291. }
  44292. else {
  44293. defines.REFRACTION = false;
  44294. }
  44295. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44296. defines.ENVIRONMENTBRDF = true;
  44297. }
  44298. else {
  44299. defines.ENVIRONMENTBRDF = false;
  44300. }
  44301. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44302. defines.ALPHAFROMALBEDO = true;
  44303. }
  44304. else {
  44305. defines.ALPHAFROMALBEDO = false;
  44306. }
  44307. }
  44308. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44309. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44310. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44311. if (!this.backFaceCulling && this._twoSidedLighting) {
  44312. defines.TWOSIDEDLIGHTING = true;
  44313. }
  44314. else {
  44315. defines.TWOSIDEDLIGHTING = false;
  44316. }
  44317. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44318. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44319. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44320. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44321. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44322. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44323. }
  44324. if (defines._areImageProcessingDirty) {
  44325. this._imageProcessingConfiguration.prepareDefines(defines);
  44326. }
  44327. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44328. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44329. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44330. // Misc.
  44331. if (defines._areMiscDirty) {
  44332. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44333. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44334. }
  44335. // Values that need to be evaluated on every frame
  44336. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44337. // Attribs
  44338. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44339. };
  44340. /**
  44341. * Force shader compilation
  44342. */
  44343. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44344. var _this = this;
  44345. var localOptions = __assign({ clipPlane: false }, options);
  44346. var defines = new PBRMaterialDefines();
  44347. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44348. if (effect.isReady()) {
  44349. if (onCompiled) {
  44350. onCompiled(this);
  44351. }
  44352. }
  44353. else {
  44354. effect.onCompileObservable.add(function () {
  44355. if (onCompiled) {
  44356. onCompiled(_this);
  44357. }
  44358. });
  44359. }
  44360. };
  44361. /**
  44362. * Initializes the uniform buffer layout for the shader.
  44363. */
  44364. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44365. // Order is important !
  44366. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44367. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44368. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44369. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44370. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44371. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44372. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44373. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44374. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44375. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44376. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44377. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44378. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44379. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44380. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44381. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44382. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44383. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44384. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44385. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44386. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44387. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44388. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44389. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44390. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44391. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44392. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44393. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44394. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44395. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44396. this._uniformBuffer.addUniform("pointSize", 1);
  44397. this._uniformBuffer.create();
  44398. };
  44399. /**
  44400. * Unbinds the textures.
  44401. */
  44402. PBRBaseMaterial.prototype.unbind = function () {
  44403. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44404. this._uniformBuffer.setTexture("reflectionSampler", null);
  44405. }
  44406. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44407. this._uniformBuffer.setTexture("refractionSampler", null);
  44408. }
  44409. _super.prototype.unbind.call(this);
  44410. };
  44411. /**
  44412. * Binds the submesh data.
  44413. * @param world - The world matrix.
  44414. * @param mesh - The BJS mesh.
  44415. * @param subMesh - A submesh of the BJS mesh.
  44416. */
  44417. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44418. var scene = this.getScene();
  44419. var defines = subMesh._materialDefines;
  44420. if (!defines) {
  44421. return;
  44422. }
  44423. var effect = subMesh.effect;
  44424. if (!effect) {
  44425. return;
  44426. }
  44427. this._activeEffect = effect;
  44428. // Matrices
  44429. this.bindOnlyWorldMatrix(world);
  44430. // Normal Matrix
  44431. if (defines.OBJECTSPACE_NORMALMAP) {
  44432. world.toNormalMatrix(this._normalMatrix);
  44433. this.bindOnlyNormalMatrix(this._normalMatrix);
  44434. }
  44435. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44436. // Bones
  44437. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44438. var reflectionTexture = null;
  44439. if (mustRebind) {
  44440. this._uniformBuffer.bindToEffect(effect, "Material");
  44441. this.bindViewProjection(effect);
  44442. reflectionTexture = this._getReflectionTexture();
  44443. var refractionTexture = this._getRefractionTexture();
  44444. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44445. // Texture uniforms
  44446. if (scene.texturesEnabled) {
  44447. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44448. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44449. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44450. }
  44451. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44452. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44453. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44454. }
  44455. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44456. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44457. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44458. }
  44459. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44460. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44461. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44462. if (reflectionTexture.boundingBoxSize) {
  44463. var cubeTexture = reflectionTexture;
  44464. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44465. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44466. }
  44467. var polynomials = reflectionTexture.sphericalPolynomial;
  44468. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44469. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44470. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44471. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44472. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44473. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44474. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44475. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44476. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44477. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44478. }
  44479. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44480. }
  44481. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44482. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44483. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44484. }
  44485. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44486. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44487. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44488. }
  44489. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44490. if (this._metallicTexture) {
  44491. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44492. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44493. }
  44494. else if (this._reflectivityTexture) {
  44495. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44496. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44497. }
  44498. if (this._microSurfaceTexture) {
  44499. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44500. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44501. }
  44502. }
  44503. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44504. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44505. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44506. if (scene._mirroredCameraPosition) {
  44507. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44508. }
  44509. else {
  44510. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44511. }
  44512. }
  44513. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44514. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44515. var depth = 1.0;
  44516. if (!refractionTexture.isCube) {
  44517. if (refractionTexture.depth) {
  44518. depth = refractionTexture.depth;
  44519. }
  44520. }
  44521. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44522. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44523. }
  44524. }
  44525. // Point size
  44526. if (this.pointsCloud) {
  44527. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44528. }
  44529. // Colors
  44530. if (defines.METALLICWORKFLOW) {
  44531. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44532. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44533. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44534. }
  44535. else {
  44536. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44537. }
  44538. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44539. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44540. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44541. // Misc
  44542. this._lightingInfos.x = this._directIntensity;
  44543. this._lightingInfos.y = this._emissiveIntensity;
  44544. this._lightingInfos.z = this._environmentIntensity;
  44545. this._lightingInfos.w = this._specularIntensity;
  44546. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44547. }
  44548. // Textures
  44549. if (scene.texturesEnabled) {
  44550. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44551. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44552. }
  44553. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44554. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44555. }
  44556. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44557. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44558. }
  44559. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44560. if (defines.LODBASEDMICROSFURACE) {
  44561. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44562. }
  44563. else {
  44564. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44565. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44566. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44567. }
  44568. }
  44569. if (defines.ENVIRONMENTBRDF) {
  44570. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44571. }
  44572. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44573. if (defines.LODBASEDMICROSFURACE) {
  44574. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44575. }
  44576. else {
  44577. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44578. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44579. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44580. }
  44581. }
  44582. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44583. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44584. }
  44585. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44586. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44587. }
  44588. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44589. if (this._metallicTexture) {
  44590. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44591. }
  44592. else if (this._reflectivityTexture) {
  44593. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44594. }
  44595. if (this._microSurfaceTexture) {
  44596. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44597. }
  44598. }
  44599. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44600. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44601. }
  44602. }
  44603. // Clip plane
  44604. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44605. // Colors
  44606. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44607. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44608. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44609. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44610. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44611. }
  44612. if (mustRebind || !this.isFrozen) {
  44613. // Lights
  44614. if (scene.lightsEnabled && !this._disableLighting) {
  44615. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44616. }
  44617. // View
  44618. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44619. this.bindView(effect);
  44620. }
  44621. // Fog
  44622. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44623. // Morph targets
  44624. if (defines.NUM_MORPH_INFLUENCERS) {
  44625. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44626. }
  44627. // image processing
  44628. this._imageProcessingConfiguration.bind(this._activeEffect);
  44629. // Log. depth
  44630. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44631. }
  44632. this._uniformBuffer.update();
  44633. this._afterBind(mesh);
  44634. };
  44635. /**
  44636. * Returns the animatable textures.
  44637. * @returns - Array of animatable textures.
  44638. */
  44639. PBRBaseMaterial.prototype.getAnimatables = function () {
  44640. var results = [];
  44641. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44642. results.push(this._albedoTexture);
  44643. }
  44644. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44645. results.push(this._ambientTexture);
  44646. }
  44647. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44648. results.push(this._opacityTexture);
  44649. }
  44650. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44651. results.push(this._reflectionTexture);
  44652. }
  44653. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44654. results.push(this._emissiveTexture);
  44655. }
  44656. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44657. results.push(this._metallicTexture);
  44658. }
  44659. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44660. results.push(this._reflectivityTexture);
  44661. }
  44662. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44663. results.push(this._bumpTexture);
  44664. }
  44665. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44666. results.push(this._lightmapTexture);
  44667. }
  44668. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44669. results.push(this._refractionTexture);
  44670. }
  44671. return results;
  44672. };
  44673. /**
  44674. * Returns the texture used for reflections.
  44675. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44676. */
  44677. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44678. if (this._reflectionTexture) {
  44679. return this._reflectionTexture;
  44680. }
  44681. return this.getScene().environmentTexture;
  44682. };
  44683. /**
  44684. * Returns the texture used for refraction or null if none is used.
  44685. * @returns - Refection texture if present. If no refraction texture and refraction
  44686. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44687. */
  44688. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44689. if (this._refractionTexture) {
  44690. return this._refractionTexture;
  44691. }
  44692. if (this._linkRefractionWithTransparency) {
  44693. return this.getScene().environmentTexture;
  44694. }
  44695. return null;
  44696. };
  44697. /**
  44698. * Disposes the resources of the material.
  44699. * @param forceDisposeEffect - Forces the disposal of effects.
  44700. * @param forceDisposeTextures - Forces the disposal of all textures.
  44701. */
  44702. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44703. if (forceDisposeTextures) {
  44704. if (this._albedoTexture) {
  44705. this._albedoTexture.dispose();
  44706. }
  44707. if (this._ambientTexture) {
  44708. this._ambientTexture.dispose();
  44709. }
  44710. if (this._opacityTexture) {
  44711. this._opacityTexture.dispose();
  44712. }
  44713. if (this._reflectionTexture) {
  44714. this._reflectionTexture.dispose();
  44715. }
  44716. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44717. this._environmentBRDFTexture.dispose();
  44718. }
  44719. if (this._emissiveTexture) {
  44720. this._emissiveTexture.dispose();
  44721. }
  44722. if (this._metallicTexture) {
  44723. this._metallicTexture.dispose();
  44724. }
  44725. if (this._reflectivityTexture) {
  44726. this._reflectivityTexture.dispose();
  44727. }
  44728. if (this._bumpTexture) {
  44729. this._bumpTexture.dispose();
  44730. }
  44731. if (this._lightmapTexture) {
  44732. this._lightmapTexture.dispose();
  44733. }
  44734. if (this._refractionTexture) {
  44735. this._refractionTexture.dispose();
  44736. }
  44737. }
  44738. this._renderTargets.dispose();
  44739. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44740. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44741. }
  44742. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44743. };
  44744. /**
  44745. * Stores the reflectivity values based on metallic roughness workflow.
  44746. */
  44747. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44748. __decorate([
  44749. BABYLON.serializeAsImageProcessingConfiguration()
  44750. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44751. __decorate([
  44752. BABYLON.serialize()
  44753. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44754. __decorate([
  44755. BABYLON.serialize()
  44756. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44757. return PBRBaseMaterial;
  44758. }(BABYLON.PushMaterial));
  44759. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44760. })(BABYLON || (BABYLON = {}));
  44761. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44762. "use strict";
  44763. var BABYLON;
  44764. (function (BABYLON) {
  44765. /**
  44766. * The Physically based simple base material of BJS.
  44767. *
  44768. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44769. * It is used as the base class for both the specGloss and metalRough conventions.
  44770. */
  44771. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44772. __extends(PBRBaseSimpleMaterial, _super);
  44773. /**
  44774. * Instantiates a new PBRMaterial instance.
  44775. *
  44776. * @param name The material name
  44777. * @param scene The scene the material will be use in.
  44778. */
  44779. function PBRBaseSimpleMaterial(name, scene) {
  44780. var _this = _super.call(this, name, scene) || this;
  44781. /**
  44782. * Number of Simultaneous lights allowed on the material.
  44783. */
  44784. _this.maxSimultaneousLights = 4;
  44785. /**
  44786. * If sets to true, disables all the lights affecting the material.
  44787. */
  44788. _this.disableLighting = false;
  44789. /**
  44790. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44791. */
  44792. _this.invertNormalMapX = false;
  44793. /**
  44794. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44795. */
  44796. _this.invertNormalMapY = false;
  44797. /**
  44798. * Emissivie color used to self-illuminate the model.
  44799. */
  44800. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44801. /**
  44802. * Occlusion Channel Strenght.
  44803. */
  44804. _this.occlusionStrength = 1.0;
  44805. _this.useLightmapAsShadowmap = false;
  44806. _this._useAlphaFromAlbedoTexture = true;
  44807. _this._useAmbientInGrayScale = true;
  44808. return _this;
  44809. }
  44810. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44811. /**
  44812. * Gets the current double sided mode.
  44813. */
  44814. get: function () {
  44815. return this._twoSidedLighting;
  44816. },
  44817. /**
  44818. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44819. */
  44820. set: function (value) {
  44821. if (this._twoSidedLighting === value) {
  44822. return;
  44823. }
  44824. this._twoSidedLighting = value;
  44825. this.backFaceCulling = !value;
  44826. this._markAllSubMeshesAsTexturesDirty();
  44827. },
  44828. enumerable: true,
  44829. configurable: true
  44830. });
  44831. /**
  44832. * Return the active textures of the material.
  44833. */
  44834. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44835. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44836. if (this.environmentTexture) {
  44837. activeTextures.push(this.environmentTexture);
  44838. }
  44839. if (this.normalTexture) {
  44840. activeTextures.push(this.normalTexture);
  44841. }
  44842. if (this.emissiveTexture) {
  44843. activeTextures.push(this.emissiveTexture);
  44844. }
  44845. if (this.occlusionTexture) {
  44846. activeTextures.push(this.occlusionTexture);
  44847. }
  44848. if (this.lightmapTexture) {
  44849. activeTextures.push(this.lightmapTexture);
  44850. }
  44851. return activeTextures;
  44852. };
  44853. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44854. if (_super.prototype.hasTexture.call(this, texture)) {
  44855. return true;
  44856. }
  44857. if (this.lightmapTexture === texture) {
  44858. return true;
  44859. }
  44860. return false;
  44861. };
  44862. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44863. return "PBRBaseSimpleMaterial";
  44864. };
  44865. __decorate([
  44866. BABYLON.serialize(),
  44867. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44868. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44869. __decorate([
  44870. BABYLON.serialize(),
  44871. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44872. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44873. __decorate([
  44874. BABYLON.serializeAsTexture(),
  44875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44876. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44877. __decorate([
  44878. BABYLON.serialize(),
  44879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44880. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44881. __decorate([
  44882. BABYLON.serialize(),
  44883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44884. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44885. __decorate([
  44886. BABYLON.serializeAsTexture(),
  44887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44888. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44889. __decorate([
  44890. BABYLON.serializeAsColor3("emissive"),
  44891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44892. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44893. __decorate([
  44894. BABYLON.serializeAsTexture(),
  44895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44896. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44897. __decorate([
  44898. BABYLON.serialize(),
  44899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44900. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44901. __decorate([
  44902. BABYLON.serializeAsTexture(),
  44903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44904. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44905. __decorate([
  44906. BABYLON.serialize(),
  44907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44908. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44909. __decorate([
  44910. BABYLON.serialize()
  44911. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44912. __decorate([
  44913. BABYLON.serializeAsTexture(),
  44914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44915. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44916. __decorate([
  44917. BABYLON.serialize(),
  44918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44919. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44920. return PBRBaseSimpleMaterial;
  44921. }(BABYLON.PBRBaseMaterial));
  44922. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44923. })(BABYLON || (BABYLON = {}));
  44924. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44925. "use strict";
  44926. var BABYLON;
  44927. (function (BABYLON) {
  44928. /**
  44929. * The Physically based material of BJS.
  44930. *
  44931. * This offers the main features of a standard PBR material.
  44932. * For more information, please refer to the documentation :
  44933. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44934. */
  44935. var PBRMaterial = /** @class */ (function (_super) {
  44936. __extends(PBRMaterial, _super);
  44937. /**
  44938. * Instantiates a new PBRMaterial instance.
  44939. *
  44940. * @param name The material name
  44941. * @param scene The scene the material will be use in.
  44942. */
  44943. function PBRMaterial(name, scene) {
  44944. var _this = _super.call(this, name, scene) || this;
  44945. /**
  44946. * Intensity of the direct lights e.g. the four lights available in your scene.
  44947. * This impacts both the direct diffuse and specular highlights.
  44948. */
  44949. _this.directIntensity = 1.0;
  44950. /**
  44951. * Intensity of the emissive part of the material.
  44952. * This helps controlling the emissive effect without modifying the emissive color.
  44953. */
  44954. _this.emissiveIntensity = 1.0;
  44955. /**
  44956. * Intensity of the environment e.g. how much the environment will light the object
  44957. * either through harmonics for rough material or through the refelction for shiny ones.
  44958. */
  44959. _this.environmentIntensity = 1.0;
  44960. /**
  44961. * This is a special control allowing the reduction of the specular highlights coming from the
  44962. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44963. */
  44964. _this.specularIntensity = 1.0;
  44965. /**
  44966. * Debug Control allowing disabling the bump map on this material.
  44967. */
  44968. _this.disableBumpMap = false;
  44969. /**
  44970. * AKA Occlusion Texture Intensity in other nomenclature.
  44971. */
  44972. _this.ambientTextureStrength = 1.0;
  44973. /**
  44974. * The color of a material in ambient lighting.
  44975. */
  44976. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44977. /**
  44978. * AKA Diffuse Color in other nomenclature.
  44979. */
  44980. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44981. /**
  44982. * AKA Specular Color in other nomenclature.
  44983. */
  44984. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44985. /**
  44986. * The color reflected from the material.
  44987. */
  44988. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44989. /**
  44990. * The color emitted from the material.
  44991. */
  44992. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44993. /**
  44994. * AKA Glossiness in other nomenclature.
  44995. */
  44996. _this.microSurface = 1.0;
  44997. /**
  44998. * source material index of refraction (IOR)' / 'destination material IOR.
  44999. */
  45000. _this.indexOfRefraction = 0.66;
  45001. /**
  45002. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45003. */
  45004. _this.invertRefractionY = false;
  45005. /**
  45006. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45007. * Materials half opaque for instance using refraction could benefit from this control.
  45008. */
  45009. _this.linkRefractionWithTransparency = false;
  45010. _this.useLightmapAsShadowmap = false;
  45011. /**
  45012. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45013. */
  45014. _this.useAlphaFromAlbedoTexture = false;
  45015. /**
  45016. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45017. */
  45018. _this.forceAlphaTest = false;
  45019. /**
  45020. * Defines the alpha limits in alpha test mode.
  45021. */
  45022. _this.alphaCutOff = 0.4;
  45023. /**
  45024. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45025. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45026. */
  45027. _this.useSpecularOverAlpha = true;
  45028. /**
  45029. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45030. */
  45031. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45032. /**
  45033. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45034. */
  45035. _this.useRoughnessFromMetallicTextureAlpha = true;
  45036. /**
  45037. * Specifies if the metallic texture contains the roughness information in its green channel.
  45038. */
  45039. _this.useRoughnessFromMetallicTextureGreen = false;
  45040. /**
  45041. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45042. */
  45043. _this.useMetallnessFromMetallicTextureBlue = false;
  45044. /**
  45045. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45046. */
  45047. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45048. /**
  45049. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45050. */
  45051. _this.useAmbientInGrayScale = false;
  45052. /**
  45053. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45054. * The material will try to infer what glossiness each pixel should be.
  45055. */
  45056. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45057. /**
  45058. * BJS is using an harcoded light falloff based on a manually sets up range.
  45059. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45060. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45061. */
  45062. _this.usePhysicalLightFalloff = true;
  45063. /**
  45064. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45065. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45066. */
  45067. _this.useRadianceOverAlpha = true;
  45068. /**
  45069. * Allows using an object space normal map (instead of tangent space).
  45070. */
  45071. _this.useObjectSpaceNormalMap = false;
  45072. /**
  45073. * Allows using the bump map in parallax mode.
  45074. */
  45075. _this.useParallax = false;
  45076. /**
  45077. * Allows using the bump map in parallax occlusion mode.
  45078. */
  45079. _this.useParallaxOcclusion = false;
  45080. /**
  45081. * Controls the scale bias of the parallax mode.
  45082. */
  45083. _this.parallaxScaleBias = 0.05;
  45084. /**
  45085. * If sets to true, disables all the lights affecting the material.
  45086. */
  45087. _this.disableLighting = false;
  45088. /**
  45089. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45090. */
  45091. _this.forceIrradianceInFragment = false;
  45092. /**
  45093. * Number of Simultaneous lights allowed on the material.
  45094. */
  45095. _this.maxSimultaneousLights = 4;
  45096. /**
  45097. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45098. */
  45099. _this.invertNormalMapX = false;
  45100. /**
  45101. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45102. */
  45103. _this.invertNormalMapY = false;
  45104. /**
  45105. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45106. */
  45107. _this.twoSidedLighting = false;
  45108. /**
  45109. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45110. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45111. */
  45112. _this.useAlphaFresnel = false;
  45113. /**
  45114. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45115. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45116. */
  45117. _this.useLinearAlphaFresnel = false;
  45118. /**
  45119. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45120. * And/Or occlude the blended part.
  45121. */
  45122. _this.environmentBRDFTexture = null;
  45123. /**
  45124. * Force normal to face away from face.
  45125. */
  45126. _this.forceNormalForward = false;
  45127. /**
  45128. * Enables specular anti aliasing in the PBR shader.
  45129. * It will both interacts on the Geometry for analytical and IBL lighting.
  45130. * It also prefilter the roughness map based on the bump values.
  45131. */
  45132. _this.enableSpecularAntiAliasing = false;
  45133. /**
  45134. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45135. * makes the reflect vector face the model (under horizon).
  45136. */
  45137. _this.useHorizonOcclusion = true;
  45138. /**
  45139. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45140. * too much the area relying on ambient texture to define their ambient occlusion.
  45141. */
  45142. _this.useRadianceOcclusion = true;
  45143. /**
  45144. * If set to true, no lighting calculations will be applied.
  45145. */
  45146. _this.unlit = false;
  45147. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45148. return _this;
  45149. }
  45150. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45151. /**
  45152. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45153. */
  45154. get: function () {
  45155. return this._PBRMATERIAL_OPAQUE;
  45156. },
  45157. enumerable: true,
  45158. configurable: true
  45159. });
  45160. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45161. /**
  45162. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45163. */
  45164. get: function () {
  45165. return this._PBRMATERIAL_ALPHATEST;
  45166. },
  45167. enumerable: true,
  45168. configurable: true
  45169. });
  45170. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45171. /**
  45172. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45173. */
  45174. get: function () {
  45175. return this._PBRMATERIAL_ALPHABLEND;
  45176. },
  45177. enumerable: true,
  45178. configurable: true
  45179. });
  45180. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45181. /**
  45182. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45183. * They are also discarded below the alpha cutoff threshold to improve performances.
  45184. */
  45185. get: function () {
  45186. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45187. },
  45188. enumerable: true,
  45189. configurable: true
  45190. });
  45191. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45192. /**
  45193. * Gets the image processing configuration used either in this material.
  45194. */
  45195. get: function () {
  45196. return this._imageProcessingConfiguration;
  45197. },
  45198. /**
  45199. * Sets the Default image processing configuration used either in the this material.
  45200. *
  45201. * If sets to null, the scene one is in use.
  45202. */
  45203. set: function (value) {
  45204. this._attachImageProcessingConfiguration(value);
  45205. // Ensure the effect will be rebuilt.
  45206. this._markAllSubMeshesAsTexturesDirty();
  45207. },
  45208. enumerable: true,
  45209. configurable: true
  45210. });
  45211. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45212. /**
  45213. * Gets wether the color curves effect is enabled.
  45214. */
  45215. get: function () {
  45216. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45217. },
  45218. /**
  45219. * Sets wether the color curves effect is enabled.
  45220. */
  45221. set: function (value) {
  45222. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45223. },
  45224. enumerable: true,
  45225. configurable: true
  45226. });
  45227. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45228. /**
  45229. * Gets wether the color grading effect is enabled.
  45230. */
  45231. get: function () {
  45232. return this.imageProcessingConfiguration.colorGradingEnabled;
  45233. },
  45234. /**
  45235. * Gets wether the color grading effect is enabled.
  45236. */
  45237. set: function (value) {
  45238. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45239. },
  45240. enumerable: true,
  45241. configurable: true
  45242. });
  45243. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45244. /**
  45245. * Gets wether tonemapping is enabled or not.
  45246. */
  45247. get: function () {
  45248. return this._imageProcessingConfiguration.toneMappingEnabled;
  45249. },
  45250. /**
  45251. * Sets wether tonemapping is enabled or not
  45252. */
  45253. set: function (value) {
  45254. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45255. },
  45256. enumerable: true,
  45257. configurable: true
  45258. });
  45259. ;
  45260. ;
  45261. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45262. /**
  45263. * The camera exposure used on this material.
  45264. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45265. * This corresponds to a photographic exposure.
  45266. */
  45267. get: function () {
  45268. return this._imageProcessingConfiguration.exposure;
  45269. },
  45270. /**
  45271. * The camera exposure used on this material.
  45272. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45273. * This corresponds to a photographic exposure.
  45274. */
  45275. set: function (value) {
  45276. this._imageProcessingConfiguration.exposure = value;
  45277. },
  45278. enumerable: true,
  45279. configurable: true
  45280. });
  45281. ;
  45282. ;
  45283. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45284. /**
  45285. * Gets The camera contrast used on this material.
  45286. */
  45287. get: function () {
  45288. return this._imageProcessingConfiguration.contrast;
  45289. },
  45290. /**
  45291. * Sets The camera contrast used on this material.
  45292. */
  45293. set: function (value) {
  45294. this._imageProcessingConfiguration.contrast = value;
  45295. },
  45296. enumerable: true,
  45297. configurable: true
  45298. });
  45299. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45300. /**
  45301. * Gets the Color Grading 2D Lookup Texture.
  45302. */
  45303. get: function () {
  45304. return this._imageProcessingConfiguration.colorGradingTexture;
  45305. },
  45306. /**
  45307. * Sets the Color Grading 2D Lookup Texture.
  45308. */
  45309. set: function (value) {
  45310. this._imageProcessingConfiguration.colorGradingTexture = value;
  45311. },
  45312. enumerable: true,
  45313. configurable: true
  45314. });
  45315. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45316. /**
  45317. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45318. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45319. * 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;
  45320. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45321. */
  45322. get: function () {
  45323. return this._imageProcessingConfiguration.colorCurves;
  45324. },
  45325. /**
  45326. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45327. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45328. * 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;
  45329. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45330. */
  45331. set: function (value) {
  45332. this._imageProcessingConfiguration.colorCurves = value;
  45333. },
  45334. enumerable: true,
  45335. configurable: true
  45336. });
  45337. /**
  45338. * Returns the name of this material class.
  45339. */
  45340. PBRMaterial.prototype.getClassName = function () {
  45341. return "PBRMaterial";
  45342. };
  45343. /**
  45344. * Returns an array of the actively used textures.
  45345. * @returns - Array of BaseTextures
  45346. */
  45347. PBRMaterial.prototype.getActiveTextures = function () {
  45348. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45349. if (this._albedoTexture) {
  45350. activeTextures.push(this._albedoTexture);
  45351. }
  45352. if (this._ambientTexture) {
  45353. activeTextures.push(this._ambientTexture);
  45354. }
  45355. if (this._opacityTexture) {
  45356. activeTextures.push(this._opacityTexture);
  45357. }
  45358. if (this._reflectionTexture) {
  45359. activeTextures.push(this._reflectionTexture);
  45360. }
  45361. if (this._emissiveTexture) {
  45362. activeTextures.push(this._emissiveTexture);
  45363. }
  45364. if (this._reflectivityTexture) {
  45365. activeTextures.push(this._reflectivityTexture);
  45366. }
  45367. if (this._metallicTexture) {
  45368. activeTextures.push(this._metallicTexture);
  45369. }
  45370. if (this._microSurfaceTexture) {
  45371. activeTextures.push(this._microSurfaceTexture);
  45372. }
  45373. if (this._bumpTexture) {
  45374. activeTextures.push(this._bumpTexture);
  45375. }
  45376. if (this._lightmapTexture) {
  45377. activeTextures.push(this._lightmapTexture);
  45378. }
  45379. if (this._refractionTexture) {
  45380. activeTextures.push(this._refractionTexture);
  45381. }
  45382. return activeTextures;
  45383. };
  45384. /**
  45385. * Checks to see if a texture is used in the material.
  45386. * @param texture - Base texture to use.
  45387. * @returns - Boolean specifying if a texture is used in the material.
  45388. */
  45389. PBRMaterial.prototype.hasTexture = function (texture) {
  45390. if (_super.prototype.hasTexture.call(this, texture)) {
  45391. return true;
  45392. }
  45393. if (this._albedoTexture === texture) {
  45394. return true;
  45395. }
  45396. if (this._ambientTexture === texture) {
  45397. return true;
  45398. }
  45399. if (this._opacityTexture === texture) {
  45400. return true;
  45401. }
  45402. if (this._reflectionTexture === texture) {
  45403. return true;
  45404. }
  45405. if (this._reflectivityTexture === texture) {
  45406. return true;
  45407. }
  45408. if (this._metallicTexture === texture) {
  45409. return true;
  45410. }
  45411. if (this._microSurfaceTexture === texture) {
  45412. return true;
  45413. }
  45414. if (this._bumpTexture === texture) {
  45415. return true;
  45416. }
  45417. if (this._lightmapTexture === texture) {
  45418. return true;
  45419. }
  45420. if (this._refractionTexture === texture) {
  45421. return true;
  45422. }
  45423. return false;
  45424. };
  45425. /**
  45426. * Makes a duplicate of the current material.
  45427. * @param name - name to use for the new material.
  45428. */
  45429. PBRMaterial.prototype.clone = function (name) {
  45430. var _this = this;
  45431. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45432. clone.id = name;
  45433. clone.name = name;
  45434. return clone;
  45435. };
  45436. /**
  45437. * Serializes this PBR Material.
  45438. * @returns - An object with the serialized material.
  45439. */
  45440. PBRMaterial.prototype.serialize = function () {
  45441. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45442. serializationObject.customType = "BABYLON.PBRMaterial";
  45443. return serializationObject;
  45444. };
  45445. // Statics
  45446. /**
  45447. * Parses a PBR Material from a serialized object.
  45448. * @param source - Serialized object.
  45449. * @param scene - BJS scene instance.
  45450. * @param rootUrl - url for the scene object
  45451. * @returns - PBRMaterial
  45452. */
  45453. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45454. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45455. };
  45456. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45457. /**
  45458. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45459. */
  45460. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45461. /**
  45462. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45463. */
  45464. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45465. /**
  45466. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45467. * They are also discarded below the alpha cutoff threshold to improve performances.
  45468. */
  45469. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45470. __decorate([
  45471. BABYLON.serialize(),
  45472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45473. ], PBRMaterial.prototype, "directIntensity", void 0);
  45474. __decorate([
  45475. BABYLON.serialize(),
  45476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45477. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45478. __decorate([
  45479. BABYLON.serialize(),
  45480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45481. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45482. __decorate([
  45483. BABYLON.serialize(),
  45484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45485. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45486. __decorate([
  45487. BABYLON.serialize(),
  45488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45489. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45490. __decorate([
  45491. BABYLON.serializeAsTexture(),
  45492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45493. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45494. __decorate([
  45495. BABYLON.serializeAsTexture(),
  45496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45497. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45498. __decorate([
  45499. BABYLON.serialize(),
  45500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45501. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45502. __decorate([
  45503. BABYLON.serializeAsTexture(),
  45504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45505. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45506. __decorate([
  45507. BABYLON.serializeAsTexture(),
  45508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45509. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45510. __decorate([
  45511. BABYLON.serializeAsTexture(),
  45512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45513. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45514. __decorate([
  45515. BABYLON.serializeAsTexture(),
  45516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45517. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45518. __decorate([
  45519. BABYLON.serializeAsTexture(),
  45520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45521. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45522. __decorate([
  45523. BABYLON.serialize(),
  45524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45525. ], PBRMaterial.prototype, "metallic", void 0);
  45526. __decorate([
  45527. BABYLON.serialize(),
  45528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45529. ], PBRMaterial.prototype, "roughness", void 0);
  45530. __decorate([
  45531. BABYLON.serializeAsTexture(),
  45532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45533. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45534. __decorate([
  45535. BABYLON.serializeAsTexture(),
  45536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45537. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45538. __decorate([
  45539. BABYLON.serializeAsTexture(),
  45540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45541. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45542. __decorate([
  45543. BABYLON.serializeAsTexture(),
  45544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45545. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45546. __decorate([
  45547. BABYLON.serializeAsColor3("ambient"),
  45548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45549. ], PBRMaterial.prototype, "ambientColor", void 0);
  45550. __decorate([
  45551. BABYLON.serializeAsColor3("albedo"),
  45552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45553. ], PBRMaterial.prototype, "albedoColor", void 0);
  45554. __decorate([
  45555. BABYLON.serializeAsColor3("reflectivity"),
  45556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45557. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45558. __decorate([
  45559. BABYLON.serializeAsColor3("reflection"),
  45560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45561. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45562. __decorate([
  45563. BABYLON.serializeAsColor3("emissive"),
  45564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45565. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45566. __decorate([
  45567. BABYLON.serialize(),
  45568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45569. ], PBRMaterial.prototype, "microSurface", void 0);
  45570. __decorate([
  45571. BABYLON.serialize(),
  45572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45573. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45574. __decorate([
  45575. BABYLON.serialize(),
  45576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45577. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45578. __decorate([
  45579. BABYLON.serialize(),
  45580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45581. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45582. __decorate([
  45583. BABYLON.serialize(),
  45584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45585. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45586. __decorate([
  45587. BABYLON.serialize(),
  45588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45589. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45590. __decorate([
  45591. BABYLON.serialize(),
  45592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45593. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45594. __decorate([
  45595. BABYLON.serialize(),
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45597. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45598. __decorate([
  45599. BABYLON.serialize(),
  45600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45601. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45602. __decorate([
  45603. BABYLON.serialize(),
  45604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45605. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45606. __decorate([
  45607. BABYLON.serialize(),
  45608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45609. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45610. __decorate([
  45611. BABYLON.serialize(),
  45612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45613. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45614. __decorate([
  45615. BABYLON.serialize(),
  45616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45617. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45618. __decorate([
  45619. BABYLON.serialize(),
  45620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45621. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45622. __decorate([
  45623. BABYLON.serialize(),
  45624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45625. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45626. __decorate([
  45627. BABYLON.serialize(),
  45628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45629. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45630. __decorate([
  45631. BABYLON.serialize(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45633. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45634. __decorate([
  45635. BABYLON.serialize(),
  45636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45637. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45638. __decorate([
  45639. BABYLON.serialize(),
  45640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45641. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45642. __decorate([
  45643. BABYLON.serialize(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45645. ], PBRMaterial.prototype, "useParallax", void 0);
  45646. __decorate([
  45647. BABYLON.serialize(),
  45648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45649. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45650. __decorate([
  45651. BABYLON.serialize(),
  45652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45653. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45654. __decorate([
  45655. BABYLON.serialize(),
  45656. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45657. ], PBRMaterial.prototype, "disableLighting", void 0);
  45658. __decorate([
  45659. BABYLON.serialize(),
  45660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45661. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45662. __decorate([
  45663. BABYLON.serialize(),
  45664. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45665. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45666. __decorate([
  45667. BABYLON.serialize(),
  45668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45669. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45670. __decorate([
  45671. BABYLON.serialize(),
  45672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45673. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45674. __decorate([
  45675. BABYLON.serialize(),
  45676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45677. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45678. __decorate([
  45679. BABYLON.serialize(),
  45680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45681. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45682. __decorate([
  45683. BABYLON.serialize(),
  45684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45685. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45686. __decorate([
  45687. BABYLON.serializeAsTexture(),
  45688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45689. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45690. __decorate([
  45691. BABYLON.serialize(),
  45692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45693. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45694. __decorate([
  45695. BABYLON.serialize(),
  45696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45697. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45698. __decorate([
  45699. BABYLON.serialize(),
  45700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45701. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45702. __decorate([
  45703. BABYLON.serialize(),
  45704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45705. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45706. __decorate([
  45707. BABYLON.serialize(),
  45708. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45709. ], PBRMaterial.prototype, "unlit", void 0);
  45710. return PBRMaterial;
  45711. }(BABYLON.PBRBaseMaterial));
  45712. BABYLON.PBRMaterial = PBRMaterial;
  45713. })(BABYLON || (BABYLON = {}));
  45714. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45715. "use strict";
  45716. var BABYLON;
  45717. (function (BABYLON) {
  45718. /**
  45719. * The PBR material of BJS following the metal roughness convention.
  45720. *
  45721. * This fits to the PBR convention in the GLTF definition:
  45722. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45723. */
  45724. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45725. __extends(PBRMetallicRoughnessMaterial, _super);
  45726. /**
  45727. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45728. *
  45729. * @param name The material name
  45730. * @param scene The scene the material will be use in.
  45731. */
  45732. function PBRMetallicRoughnessMaterial(name, scene) {
  45733. var _this = _super.call(this, name, scene) || this;
  45734. _this._useRoughnessFromMetallicTextureAlpha = false;
  45735. _this._useRoughnessFromMetallicTextureGreen = true;
  45736. _this._useMetallnessFromMetallicTextureBlue = true;
  45737. _this.metallic = 1.0;
  45738. _this.roughness = 1.0;
  45739. return _this;
  45740. }
  45741. /**
  45742. * Return the currrent class name of the material.
  45743. */
  45744. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45745. return "PBRMetallicRoughnessMaterial";
  45746. };
  45747. /**
  45748. * Return the active textures of the material.
  45749. */
  45750. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45751. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45752. if (this.baseTexture) {
  45753. activeTextures.push(this.baseTexture);
  45754. }
  45755. if (this.metallicRoughnessTexture) {
  45756. activeTextures.push(this.metallicRoughnessTexture);
  45757. }
  45758. return activeTextures;
  45759. };
  45760. /**
  45761. * Checks to see if a texture is used in the material.
  45762. * @param texture - Base texture to use.
  45763. * @returns - Boolean specifying if a texture is used in the material.
  45764. */
  45765. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45766. if (_super.prototype.hasTexture.call(this, texture)) {
  45767. return true;
  45768. }
  45769. if (this.baseTexture === texture) {
  45770. return true;
  45771. }
  45772. if (this.metallicRoughnessTexture === texture) {
  45773. return true;
  45774. }
  45775. return false;
  45776. };
  45777. /**
  45778. * Makes a duplicate of the current material.
  45779. * @param name - name to use for the new material.
  45780. */
  45781. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45782. var _this = this;
  45783. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45784. clone.id = name;
  45785. clone.name = name;
  45786. return clone;
  45787. };
  45788. /**
  45789. * Serialize the material to a parsable JSON object.
  45790. */
  45791. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45792. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45793. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45794. return serializationObject;
  45795. };
  45796. /**
  45797. * Parses a JSON object correponding to the serialize function.
  45798. */
  45799. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45800. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45801. };
  45802. __decorate([
  45803. BABYLON.serializeAsColor3(),
  45804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45805. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45806. __decorate([
  45807. BABYLON.serializeAsTexture(),
  45808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45809. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45810. __decorate([
  45811. BABYLON.serialize(),
  45812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45813. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45814. __decorate([
  45815. BABYLON.serialize(),
  45816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45817. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45818. __decorate([
  45819. BABYLON.serializeAsTexture(),
  45820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45821. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45822. return PBRMetallicRoughnessMaterial;
  45823. }(BABYLON.PBRBaseSimpleMaterial));
  45824. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45825. })(BABYLON || (BABYLON = {}));
  45826. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45827. "use strict";
  45828. var BABYLON;
  45829. (function (BABYLON) {
  45830. /**
  45831. * The PBR material of BJS following the specular glossiness convention.
  45832. *
  45833. * This fits to the PBR convention in the GLTF definition:
  45834. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45835. */
  45836. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45837. __extends(PBRSpecularGlossinessMaterial, _super);
  45838. /**
  45839. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45840. *
  45841. * @param name The material name
  45842. * @param scene The scene the material will be use in.
  45843. */
  45844. function PBRSpecularGlossinessMaterial(name, scene) {
  45845. var _this = _super.call(this, name, scene) || this;
  45846. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45847. return _this;
  45848. }
  45849. /**
  45850. * Return the currrent class name of the material.
  45851. */
  45852. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45853. return "PBRSpecularGlossinessMaterial";
  45854. };
  45855. /**
  45856. * Return the active textures of the material.
  45857. */
  45858. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45859. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45860. if (this.diffuseTexture) {
  45861. activeTextures.push(this.diffuseTexture);
  45862. }
  45863. if (this.specularGlossinessTexture) {
  45864. activeTextures.push(this.specularGlossinessTexture);
  45865. }
  45866. return activeTextures;
  45867. };
  45868. /**
  45869. * Checks to see if a texture is used in the material.
  45870. * @param texture - Base texture to use.
  45871. * @returns - Boolean specifying if a texture is used in the material.
  45872. */
  45873. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45874. if (_super.prototype.hasTexture.call(this, texture)) {
  45875. return true;
  45876. }
  45877. if (this.diffuseTexture === texture) {
  45878. return true;
  45879. }
  45880. if (this.specularGlossinessTexture === texture) {
  45881. return true;
  45882. }
  45883. return false;
  45884. };
  45885. /**
  45886. * Makes a duplicate of the current material.
  45887. * @param name - name to use for the new material.
  45888. */
  45889. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45890. var _this = this;
  45891. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45892. clone.id = name;
  45893. clone.name = name;
  45894. return clone;
  45895. };
  45896. /**
  45897. * Serialize the material to a parsable JSON object.
  45898. */
  45899. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45900. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45901. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45902. return serializationObject;
  45903. };
  45904. /**
  45905. * Parses a JSON object correponding to the serialize function.
  45906. */
  45907. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45908. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45909. };
  45910. __decorate([
  45911. BABYLON.serializeAsColor3("diffuse"),
  45912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45913. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45914. __decorate([
  45915. BABYLON.serializeAsTexture(),
  45916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45917. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45918. __decorate([
  45919. BABYLON.serializeAsColor3("specular"),
  45920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45921. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45922. __decorate([
  45923. BABYLON.serialize(),
  45924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45925. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45926. __decorate([
  45927. BABYLON.serializeAsTexture(),
  45928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45929. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45930. return PBRSpecularGlossinessMaterial;
  45931. }(BABYLON.PBRBaseSimpleMaterial));
  45932. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45933. })(BABYLON || (BABYLON = {}));
  45934. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45935. "use strict";
  45936. var BABYLON;
  45937. (function (BABYLON) {
  45938. BABYLON.CameraInputTypes = {};
  45939. var CameraInputsManager = /** @class */ (function () {
  45940. function CameraInputsManager(camera) {
  45941. this.attached = {};
  45942. this.camera = camera;
  45943. this.checkInputs = function () { };
  45944. }
  45945. /**
  45946. * Add an input method to a camera.
  45947. * builtin inputs example: camera.inputs.addGamepad();
  45948. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45949. * @param input camera input method
  45950. */
  45951. CameraInputsManager.prototype.add = function (input) {
  45952. var type = input.getSimpleName();
  45953. if (this.attached[type]) {
  45954. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45955. return;
  45956. }
  45957. this.attached[type] = input;
  45958. input.camera = this.camera;
  45959. //for checkInputs, we are dynamically creating a function
  45960. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45961. if (input.checkInputs) {
  45962. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45963. }
  45964. if (this.attachedElement) {
  45965. input.attachControl(this.attachedElement);
  45966. }
  45967. };
  45968. /**
  45969. * Remove a specific input method from a camera
  45970. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45971. * @param inputToRemove camera input method
  45972. */
  45973. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45974. for (var cam in this.attached) {
  45975. var input = this.attached[cam];
  45976. if (input === inputToRemove) {
  45977. input.detachControl(this.attachedElement);
  45978. input.camera = null;
  45979. delete this.attached[cam];
  45980. this.rebuildInputCheck();
  45981. }
  45982. }
  45983. };
  45984. CameraInputsManager.prototype.removeByType = function (inputType) {
  45985. for (var cam in this.attached) {
  45986. var input = this.attached[cam];
  45987. if (input.getClassName() === inputType) {
  45988. input.detachControl(this.attachedElement);
  45989. input.camera = null;
  45990. delete this.attached[cam];
  45991. this.rebuildInputCheck();
  45992. }
  45993. }
  45994. };
  45995. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45996. var current = this.checkInputs;
  45997. return function () {
  45998. current();
  45999. fn();
  46000. };
  46001. };
  46002. CameraInputsManager.prototype.attachInput = function (input) {
  46003. if (this.attachedElement) {
  46004. input.attachControl(this.attachedElement, this.noPreventDefault);
  46005. }
  46006. };
  46007. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46008. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46009. if (this.attachedElement) {
  46010. return;
  46011. }
  46012. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46013. this.attachedElement = element;
  46014. this.noPreventDefault = noPreventDefault;
  46015. for (var cam in this.attached) {
  46016. this.attached[cam].attachControl(element, noPreventDefault);
  46017. }
  46018. };
  46019. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46020. if (disconnect === void 0) { disconnect = false; }
  46021. if (this.attachedElement !== element) {
  46022. return;
  46023. }
  46024. for (var cam in this.attached) {
  46025. this.attached[cam].detachControl(element);
  46026. if (disconnect) {
  46027. this.attached[cam].camera = null;
  46028. }
  46029. }
  46030. this.attachedElement = null;
  46031. };
  46032. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46033. this.checkInputs = function () { };
  46034. for (var cam in this.attached) {
  46035. var input = this.attached[cam];
  46036. if (input.checkInputs) {
  46037. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46038. }
  46039. }
  46040. };
  46041. /**
  46042. * Remove all attached input methods from a camera
  46043. */
  46044. CameraInputsManager.prototype.clear = function () {
  46045. if (this.attachedElement) {
  46046. this.detachElement(this.attachedElement, true);
  46047. }
  46048. this.attached = {};
  46049. this.attachedElement = null;
  46050. this.checkInputs = function () { };
  46051. };
  46052. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46053. var inputs = {};
  46054. for (var cam in this.attached) {
  46055. var input = this.attached[cam];
  46056. var res = BABYLON.SerializationHelper.Serialize(input);
  46057. inputs[input.getClassName()] = res;
  46058. }
  46059. serializedCamera.inputsmgr = inputs;
  46060. };
  46061. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46062. var parsedInputs = parsedCamera.inputsmgr;
  46063. if (parsedInputs) {
  46064. this.clear();
  46065. for (var n in parsedInputs) {
  46066. var construct = BABYLON.CameraInputTypes[n];
  46067. if (construct) {
  46068. var parsedinput = parsedInputs[n];
  46069. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46070. this.add(input);
  46071. }
  46072. }
  46073. }
  46074. else {
  46075. //2016-03-08 this part is for managing backward compatibility
  46076. for (var n in this.attached) {
  46077. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46078. if (construct) {
  46079. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46080. this.remove(this.attached[n]);
  46081. this.add(input);
  46082. }
  46083. }
  46084. }
  46085. };
  46086. return CameraInputsManager;
  46087. }());
  46088. BABYLON.CameraInputsManager = CameraInputsManager;
  46089. })(BABYLON || (BABYLON = {}));
  46090. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46091. "use strict";
  46092. var BABYLON;
  46093. (function (BABYLON) {
  46094. var TargetCamera = /** @class */ (function (_super) {
  46095. __extends(TargetCamera, _super);
  46096. function TargetCamera(name, position, scene) {
  46097. var _this = _super.call(this, name, position, scene) || this;
  46098. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46099. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46100. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46101. _this.speed = 2.0;
  46102. _this.noRotationConstraint = false;
  46103. _this.lockedTarget = null;
  46104. _this._currentTarget = BABYLON.Vector3.Zero();
  46105. _this._viewMatrix = BABYLON.Matrix.Zero();
  46106. _this._camMatrix = BABYLON.Matrix.Zero();
  46107. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46108. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46109. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46110. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46111. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46112. _this._lookAtTemp = BABYLON.Matrix.Zero();
  46113. _this._tempMatrix = BABYLON.Matrix.Zero();
  46114. return _this;
  46115. }
  46116. TargetCamera.prototype.getFrontPosition = function (distance) {
  46117. this.getWorldMatrix();
  46118. var direction = this.getTarget().subtract(this.position);
  46119. direction.normalize();
  46120. direction.scaleInPlace(distance);
  46121. return this.globalPosition.add(direction);
  46122. };
  46123. TargetCamera.prototype._getLockedTargetPosition = function () {
  46124. if (!this.lockedTarget) {
  46125. return null;
  46126. }
  46127. if (this.lockedTarget.absolutePosition) {
  46128. this.lockedTarget.computeWorldMatrix();
  46129. }
  46130. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46131. };
  46132. TargetCamera.prototype.storeState = function () {
  46133. this._storedPosition = this.position.clone();
  46134. this._storedRotation = this.rotation.clone();
  46135. if (this.rotationQuaternion) {
  46136. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46137. }
  46138. return _super.prototype.storeState.call(this);
  46139. };
  46140. /**
  46141. * Restored camera state. You must call storeState() first
  46142. */
  46143. TargetCamera.prototype._restoreStateValues = function () {
  46144. if (!_super.prototype._restoreStateValues.call(this)) {
  46145. return false;
  46146. }
  46147. this.position = this._storedPosition.clone();
  46148. this.rotation = this._storedRotation.clone();
  46149. if (this.rotationQuaternion) {
  46150. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46151. }
  46152. this.cameraDirection.copyFromFloats(0, 0, 0);
  46153. this.cameraRotation.copyFromFloats(0, 0);
  46154. return true;
  46155. };
  46156. // Cache
  46157. TargetCamera.prototype._initCache = function () {
  46158. _super.prototype._initCache.call(this);
  46159. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46160. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46161. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46162. };
  46163. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46164. if (!ignoreParentClass) {
  46165. _super.prototype._updateCache.call(this);
  46166. }
  46167. var lockedTargetPosition = this._getLockedTargetPosition();
  46168. if (!lockedTargetPosition) {
  46169. this._cache.lockedTarget = null;
  46170. }
  46171. else {
  46172. if (!this._cache.lockedTarget) {
  46173. this._cache.lockedTarget = lockedTargetPosition.clone();
  46174. }
  46175. else {
  46176. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46177. }
  46178. }
  46179. this._cache.rotation.copyFrom(this.rotation);
  46180. if (this.rotationQuaternion)
  46181. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46182. };
  46183. // Synchronized
  46184. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46185. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46186. return false;
  46187. }
  46188. var lockedTargetPosition = this._getLockedTargetPosition();
  46189. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46190. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46191. };
  46192. // Methods
  46193. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46194. var engine = this.getEngine();
  46195. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46196. };
  46197. // Target
  46198. TargetCamera.prototype.setTarget = function (target) {
  46199. this.upVector.normalize();
  46200. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46201. this._camMatrix.invert();
  46202. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46203. var vDir = target.subtract(this.position);
  46204. if (vDir.x >= 0.0) {
  46205. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46206. }
  46207. else {
  46208. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46209. }
  46210. this.rotation.z = 0;
  46211. if (isNaN(this.rotation.x)) {
  46212. this.rotation.x = 0;
  46213. }
  46214. if (isNaN(this.rotation.y)) {
  46215. this.rotation.y = 0;
  46216. }
  46217. if (isNaN(this.rotation.z)) {
  46218. this.rotation.z = 0;
  46219. }
  46220. if (this.rotationQuaternion) {
  46221. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46222. }
  46223. };
  46224. /**
  46225. * Return the current target position of the camera. This value is expressed in local space.
  46226. */
  46227. TargetCamera.prototype.getTarget = function () {
  46228. return this._currentTarget;
  46229. };
  46230. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46231. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46232. };
  46233. TargetCamera.prototype._updatePosition = function () {
  46234. if (this.parent) {
  46235. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46236. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46237. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46238. return;
  46239. }
  46240. this.position.addInPlace(this.cameraDirection);
  46241. };
  46242. TargetCamera.prototype._checkInputs = function () {
  46243. var needToMove = this._decideIfNeedsToMove();
  46244. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46245. // Move
  46246. if (needToMove) {
  46247. this._updatePosition();
  46248. }
  46249. // Rotate
  46250. if (needToRotate) {
  46251. this.rotation.x += this.cameraRotation.x;
  46252. this.rotation.y += this.cameraRotation.y;
  46253. //rotate, if quaternion is set and rotation was used
  46254. if (this.rotationQuaternion) {
  46255. var len = this.rotation.lengthSquared();
  46256. if (len) {
  46257. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46258. }
  46259. }
  46260. if (!this.noRotationConstraint) {
  46261. var limit = (Math.PI / 2) * 0.95;
  46262. if (this.rotation.x > limit)
  46263. this.rotation.x = limit;
  46264. if (this.rotation.x < -limit)
  46265. this.rotation.x = -limit;
  46266. }
  46267. }
  46268. // Inertia
  46269. if (needToMove) {
  46270. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46271. this.cameraDirection.x = 0;
  46272. }
  46273. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46274. this.cameraDirection.y = 0;
  46275. }
  46276. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46277. this.cameraDirection.z = 0;
  46278. }
  46279. this.cameraDirection.scaleInPlace(this.inertia);
  46280. }
  46281. if (needToRotate) {
  46282. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46283. this.cameraRotation.x = 0;
  46284. }
  46285. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46286. this.cameraRotation.y = 0;
  46287. }
  46288. this.cameraRotation.scaleInPlace(this.inertia);
  46289. }
  46290. _super.prototype._checkInputs.call(this);
  46291. };
  46292. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46293. if (this.rotationQuaternion) {
  46294. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46295. }
  46296. else {
  46297. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46298. }
  46299. //update the up vector!
  46300. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46301. };
  46302. TargetCamera.prototype._getViewMatrix = function () {
  46303. if (this.lockedTarget) {
  46304. this.setTarget(this._getLockedTargetPosition());
  46305. }
  46306. // Compute
  46307. this._updateCameraRotationMatrix();
  46308. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46309. // Computing target and final matrix
  46310. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46311. if (this.getScene().useRightHandedSystem) {
  46312. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46313. }
  46314. else {
  46315. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46316. }
  46317. return this._viewMatrix;
  46318. };
  46319. /**
  46320. * @override
  46321. * Override Camera.createRigCamera
  46322. */
  46323. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46324. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46325. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46326. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46327. if (!this.rotationQuaternion) {
  46328. this.rotationQuaternion = new BABYLON.Quaternion();
  46329. }
  46330. rigCamera._cameraRigParams = {};
  46331. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46332. }
  46333. return rigCamera;
  46334. }
  46335. return null;
  46336. };
  46337. /**
  46338. * @override
  46339. * Override Camera._updateRigCameras
  46340. */
  46341. TargetCamera.prototype._updateRigCameras = function () {
  46342. var camLeft = this._rigCameras[0];
  46343. var camRight = this._rigCameras[1];
  46344. switch (this.cameraRigMode) {
  46345. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46346. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46347. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46348. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46349. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46350. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46351. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46352. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46353. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46354. camLeft.setTarget(this.getTarget());
  46355. camRight.setTarget(this.getTarget());
  46356. break;
  46357. case BABYLON.Camera.RIG_MODE_VR:
  46358. if (camLeft.rotationQuaternion) {
  46359. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46360. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46361. }
  46362. else {
  46363. camLeft.rotation.copyFrom(this.rotation);
  46364. camRight.rotation.copyFrom(this.rotation);
  46365. }
  46366. camLeft.position.copyFrom(this.position);
  46367. camRight.position.copyFrom(this.position);
  46368. break;
  46369. }
  46370. _super.prototype._updateRigCameras.call(this);
  46371. };
  46372. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46373. if (!this._rigCamTransformMatrix) {
  46374. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46375. }
  46376. var target = this.getTarget();
  46377. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46378. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46379. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46380. };
  46381. TargetCamera.prototype.getClassName = function () {
  46382. return "TargetCamera";
  46383. };
  46384. __decorate([
  46385. BABYLON.serializeAsVector3()
  46386. ], TargetCamera.prototype, "rotation", void 0);
  46387. __decorate([
  46388. BABYLON.serialize()
  46389. ], TargetCamera.prototype, "speed", void 0);
  46390. __decorate([
  46391. BABYLON.serializeAsMeshReference("lockedTargetId")
  46392. ], TargetCamera.prototype, "lockedTarget", void 0);
  46393. return TargetCamera;
  46394. }(BABYLON.Camera));
  46395. BABYLON.TargetCamera = TargetCamera;
  46396. })(BABYLON || (BABYLON = {}));
  46397. //# sourceMappingURL=babylon.targetCamera.js.map
  46398. "use strict";
  46399. var BABYLON;
  46400. (function (BABYLON) {
  46401. var FreeCameraMouseInput = /** @class */ (function () {
  46402. function FreeCameraMouseInput(touchEnabled) {
  46403. if (touchEnabled === void 0) { touchEnabled = true; }
  46404. this.touchEnabled = touchEnabled;
  46405. this.buttons = [0, 1, 2];
  46406. this.angularSensibility = 2000.0;
  46407. this.previousPosition = null;
  46408. }
  46409. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46410. var _this = this;
  46411. var engine = this.camera.getEngine();
  46412. if (!this._pointerInput) {
  46413. this._pointerInput = function (p, s) {
  46414. var evt = p.event;
  46415. if (engine.isInVRExclusivePointerMode) {
  46416. return;
  46417. }
  46418. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46419. return;
  46420. }
  46421. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46422. return;
  46423. }
  46424. var srcElement = (evt.srcElement || evt.target);
  46425. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46426. try {
  46427. srcElement.setPointerCapture(evt.pointerId);
  46428. }
  46429. catch (e) {
  46430. //Nothing to do with the error. Execution will continue.
  46431. }
  46432. _this.previousPosition = {
  46433. x: evt.clientX,
  46434. y: evt.clientY
  46435. };
  46436. if (!noPreventDefault) {
  46437. evt.preventDefault();
  46438. element.focus();
  46439. }
  46440. }
  46441. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46442. try {
  46443. srcElement.releasePointerCapture(evt.pointerId);
  46444. }
  46445. catch (e) {
  46446. //Nothing to do with the error.
  46447. }
  46448. _this.previousPosition = null;
  46449. if (!noPreventDefault) {
  46450. evt.preventDefault();
  46451. }
  46452. }
  46453. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46454. if (!_this.previousPosition || engine.isPointerLock) {
  46455. return;
  46456. }
  46457. var offsetX = evt.clientX - _this.previousPosition.x;
  46458. var offsetY = evt.clientY - _this.previousPosition.y;
  46459. if (_this.camera.getScene().useRightHandedSystem) {
  46460. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46461. }
  46462. else {
  46463. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46464. }
  46465. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46466. _this.previousPosition = {
  46467. x: evt.clientX,
  46468. y: evt.clientY
  46469. };
  46470. if (!noPreventDefault) {
  46471. evt.preventDefault();
  46472. }
  46473. }
  46474. };
  46475. }
  46476. this._onMouseMove = function (evt) {
  46477. if (!engine.isPointerLock) {
  46478. return;
  46479. }
  46480. if (engine.isInVRExclusivePointerMode) {
  46481. return;
  46482. }
  46483. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46484. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46485. if (_this.camera.getScene().useRightHandedSystem) {
  46486. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46487. }
  46488. else {
  46489. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46490. }
  46491. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46492. _this.previousPosition = null;
  46493. if (!noPreventDefault) {
  46494. evt.preventDefault();
  46495. }
  46496. };
  46497. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46498. element.addEventListener("mousemove", this._onMouseMove, false);
  46499. };
  46500. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46501. if (this._observer && element) {
  46502. this.camera.getScene().onPointerObservable.remove(this._observer);
  46503. if (this._onMouseMove) {
  46504. element.removeEventListener("mousemove", this._onMouseMove);
  46505. }
  46506. this._observer = null;
  46507. this._onMouseMove = null;
  46508. this.previousPosition = null;
  46509. }
  46510. };
  46511. FreeCameraMouseInput.prototype.getClassName = function () {
  46512. return "FreeCameraMouseInput";
  46513. };
  46514. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46515. return "mouse";
  46516. };
  46517. __decorate([
  46518. BABYLON.serialize()
  46519. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46520. __decorate([
  46521. BABYLON.serialize()
  46522. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46523. return FreeCameraMouseInput;
  46524. }());
  46525. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46526. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46527. })(BABYLON || (BABYLON = {}));
  46528. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46529. "use strict";
  46530. var BABYLON;
  46531. (function (BABYLON) {
  46532. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46533. function FreeCameraKeyboardMoveInput() {
  46534. this._keys = new Array();
  46535. this.keysUp = [38];
  46536. this.keysDown = [40];
  46537. this.keysLeft = [37];
  46538. this.keysRight = [39];
  46539. }
  46540. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46541. var _this = this;
  46542. if (this._onCanvasBlurObserver) {
  46543. return;
  46544. }
  46545. this._scene = this.camera.getScene();
  46546. this._engine = this._scene.getEngine();
  46547. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46548. _this._keys = [];
  46549. });
  46550. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46551. var evt = info.event;
  46552. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46553. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46554. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46555. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46556. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46557. var index = _this._keys.indexOf(evt.keyCode);
  46558. if (index === -1) {
  46559. _this._keys.push(evt.keyCode);
  46560. }
  46561. if (!noPreventDefault) {
  46562. evt.preventDefault();
  46563. }
  46564. }
  46565. }
  46566. else {
  46567. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46568. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46569. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46570. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46571. var index = _this._keys.indexOf(evt.keyCode);
  46572. if (index >= 0) {
  46573. _this._keys.splice(index, 1);
  46574. }
  46575. if (!noPreventDefault) {
  46576. evt.preventDefault();
  46577. }
  46578. }
  46579. }
  46580. });
  46581. };
  46582. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46583. if (this._scene) {
  46584. if (this._onKeyboardObserver) {
  46585. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46586. }
  46587. if (this._onCanvasBlurObserver) {
  46588. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46589. }
  46590. this._onKeyboardObserver = null;
  46591. this._onCanvasBlurObserver = null;
  46592. }
  46593. this._keys = [];
  46594. };
  46595. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46596. if (this._onKeyboardObserver) {
  46597. var camera = this.camera;
  46598. // Keyboard
  46599. for (var index = 0; index < this._keys.length; index++) {
  46600. var keyCode = this._keys[index];
  46601. var speed = camera._computeLocalCameraSpeed();
  46602. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46603. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46604. }
  46605. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46606. camera._localDirection.copyFromFloats(0, 0, speed);
  46607. }
  46608. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46609. camera._localDirection.copyFromFloats(speed, 0, 0);
  46610. }
  46611. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46612. camera._localDirection.copyFromFloats(0, 0, -speed);
  46613. }
  46614. if (camera.getScene().useRightHandedSystem) {
  46615. camera._localDirection.z *= -1;
  46616. }
  46617. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46618. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46619. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46620. }
  46621. }
  46622. };
  46623. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46624. return "FreeCameraKeyboardMoveInput";
  46625. };
  46626. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46627. this._keys = [];
  46628. };
  46629. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46630. return "keyboard";
  46631. };
  46632. __decorate([
  46633. BABYLON.serialize()
  46634. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46635. __decorate([
  46636. BABYLON.serialize()
  46637. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46638. __decorate([
  46639. BABYLON.serialize()
  46640. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46641. __decorate([
  46642. BABYLON.serialize()
  46643. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46644. return FreeCameraKeyboardMoveInput;
  46645. }());
  46646. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46647. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46648. })(BABYLON || (BABYLON = {}));
  46649. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46650. "use strict";
  46651. var BABYLON;
  46652. (function (BABYLON) {
  46653. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46654. __extends(FreeCameraInputsManager, _super);
  46655. function FreeCameraInputsManager(camera) {
  46656. return _super.call(this, camera) || this;
  46657. }
  46658. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46659. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46660. return this;
  46661. };
  46662. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46663. if (touchEnabled === void 0) { touchEnabled = true; }
  46664. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46665. return this;
  46666. };
  46667. FreeCameraInputsManager.prototype.addGamepad = function () {
  46668. this.add(new BABYLON.FreeCameraGamepadInput());
  46669. return this;
  46670. };
  46671. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46672. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46673. return this;
  46674. };
  46675. FreeCameraInputsManager.prototype.addTouch = function () {
  46676. this.add(new BABYLON.FreeCameraTouchInput());
  46677. return this;
  46678. };
  46679. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46680. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46681. return this;
  46682. };
  46683. return FreeCameraInputsManager;
  46684. }(BABYLON.CameraInputsManager));
  46685. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46686. })(BABYLON || (BABYLON = {}));
  46687. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46688. "use strict";
  46689. var BABYLON;
  46690. (function (BABYLON) {
  46691. var FreeCamera = /** @class */ (function (_super) {
  46692. __extends(FreeCamera, _super);
  46693. function FreeCamera(name, position, scene) {
  46694. var _this = _super.call(this, name, position, scene) || this;
  46695. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46696. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46697. _this.checkCollisions = false;
  46698. _this.applyGravity = false;
  46699. _this._needMoveForGravity = false;
  46700. _this._oldPosition = BABYLON.Vector3.Zero();
  46701. _this._diffPosition = BABYLON.Vector3.Zero();
  46702. _this._newPosition = BABYLON.Vector3.Zero();
  46703. // Collisions
  46704. _this._collisionMask = -1;
  46705. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46706. if (collidedMesh === void 0) { collidedMesh = null; }
  46707. //TODO move this to the collision coordinator!
  46708. if (_this.getScene().workerCollisions)
  46709. newPosition.multiplyInPlace(_this._collider._radius);
  46710. var updatePosition = function (newPos) {
  46711. _this._newPosition.copyFrom(newPos);
  46712. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46713. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46714. _this.position.addInPlace(_this._diffPosition);
  46715. if (_this.onCollide && collidedMesh) {
  46716. _this.onCollide(collidedMesh);
  46717. }
  46718. }
  46719. };
  46720. updatePosition(newPosition);
  46721. };
  46722. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46723. _this.inputs.addKeyboard().addMouse();
  46724. return _this;
  46725. }
  46726. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46727. //-- begin properties for backward compatibility for inputs
  46728. /**
  46729. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46730. * Higher values reduce sensitivity.
  46731. */
  46732. get: function () {
  46733. var mouse = this.inputs.attached["mouse"];
  46734. if (mouse)
  46735. return mouse.angularSensibility;
  46736. return 0;
  46737. },
  46738. /**
  46739. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46740. * Higher values reduce sensitivity.
  46741. */
  46742. set: function (value) {
  46743. var mouse = this.inputs.attached["mouse"];
  46744. if (mouse)
  46745. mouse.angularSensibility = value;
  46746. },
  46747. enumerable: true,
  46748. configurable: true
  46749. });
  46750. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46751. get: function () {
  46752. var keyboard = this.inputs.attached["keyboard"];
  46753. if (keyboard)
  46754. return keyboard.keysUp;
  46755. return [];
  46756. },
  46757. set: function (value) {
  46758. var keyboard = this.inputs.attached["keyboard"];
  46759. if (keyboard)
  46760. keyboard.keysUp = value;
  46761. },
  46762. enumerable: true,
  46763. configurable: true
  46764. });
  46765. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46766. get: function () {
  46767. var keyboard = this.inputs.attached["keyboard"];
  46768. if (keyboard)
  46769. return keyboard.keysDown;
  46770. return [];
  46771. },
  46772. set: function (value) {
  46773. var keyboard = this.inputs.attached["keyboard"];
  46774. if (keyboard)
  46775. keyboard.keysDown = value;
  46776. },
  46777. enumerable: true,
  46778. configurable: true
  46779. });
  46780. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46781. get: function () {
  46782. var keyboard = this.inputs.attached["keyboard"];
  46783. if (keyboard)
  46784. return keyboard.keysLeft;
  46785. return [];
  46786. },
  46787. set: function (value) {
  46788. var keyboard = this.inputs.attached["keyboard"];
  46789. if (keyboard)
  46790. keyboard.keysLeft = value;
  46791. },
  46792. enumerable: true,
  46793. configurable: true
  46794. });
  46795. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46796. get: function () {
  46797. var keyboard = this.inputs.attached["keyboard"];
  46798. if (keyboard)
  46799. return keyboard.keysRight;
  46800. return [];
  46801. },
  46802. set: function (value) {
  46803. var keyboard = this.inputs.attached["keyboard"];
  46804. if (keyboard)
  46805. keyboard.keysRight = value;
  46806. },
  46807. enumerable: true,
  46808. configurable: true
  46809. });
  46810. // Controls
  46811. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46812. this.inputs.attachElement(element, noPreventDefault);
  46813. };
  46814. FreeCamera.prototype.detachControl = function (element) {
  46815. this.inputs.detachElement(element);
  46816. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46817. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46818. };
  46819. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46820. get: function () {
  46821. return this._collisionMask;
  46822. },
  46823. set: function (mask) {
  46824. this._collisionMask = !isNaN(mask) ? mask : -1;
  46825. },
  46826. enumerable: true,
  46827. configurable: true
  46828. });
  46829. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46830. var globalPosition;
  46831. if (this.parent) {
  46832. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46833. }
  46834. else {
  46835. globalPosition = this.position;
  46836. }
  46837. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46838. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46839. if (!this._collider) {
  46840. this._collider = new BABYLON.Collider();
  46841. }
  46842. this._collider._radius = this.ellipsoid;
  46843. this._collider.collisionMask = this._collisionMask;
  46844. //no need for clone, as long as gravity is not on.
  46845. var actualDisplacement = displacement;
  46846. //add gravity to the direction to prevent the dual-collision checking
  46847. if (this.applyGravity) {
  46848. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46849. actualDisplacement = displacement.add(this.getScene().gravity);
  46850. }
  46851. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46852. };
  46853. FreeCamera.prototype._checkInputs = function () {
  46854. if (!this._localDirection) {
  46855. this._localDirection = BABYLON.Vector3.Zero();
  46856. this._transformedDirection = BABYLON.Vector3.Zero();
  46857. }
  46858. this.inputs.checkInputs();
  46859. _super.prototype._checkInputs.call(this);
  46860. };
  46861. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46862. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46863. };
  46864. FreeCamera.prototype._updatePosition = function () {
  46865. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46866. this._collideWithWorld(this.cameraDirection);
  46867. }
  46868. else {
  46869. _super.prototype._updatePosition.call(this);
  46870. }
  46871. };
  46872. FreeCamera.prototype.dispose = function () {
  46873. this.inputs.clear();
  46874. _super.prototype.dispose.call(this);
  46875. };
  46876. FreeCamera.prototype.getClassName = function () {
  46877. return "FreeCamera";
  46878. };
  46879. __decorate([
  46880. BABYLON.serializeAsVector3()
  46881. ], FreeCamera.prototype, "ellipsoid", void 0);
  46882. __decorate([
  46883. BABYLON.serializeAsVector3()
  46884. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46885. __decorate([
  46886. BABYLON.serialize()
  46887. ], FreeCamera.prototype, "checkCollisions", void 0);
  46888. __decorate([
  46889. BABYLON.serialize()
  46890. ], FreeCamera.prototype, "applyGravity", void 0);
  46891. return FreeCamera;
  46892. }(BABYLON.TargetCamera));
  46893. BABYLON.FreeCamera = FreeCamera;
  46894. })(BABYLON || (BABYLON = {}));
  46895. //# sourceMappingURL=babylon.freeCamera.js.map
  46896. "use strict";
  46897. var BABYLON;
  46898. (function (BABYLON) {
  46899. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46900. function ArcRotateCameraKeyboardMoveInput() {
  46901. this._keys = new Array();
  46902. this.keysUp = [38];
  46903. this.keysDown = [40];
  46904. this.keysLeft = [37];
  46905. this.keysRight = [39];
  46906. this.keysReset = [220];
  46907. this.panningSensibility = 50.0;
  46908. this.zoomingSensibility = 25.0;
  46909. this.useAltToZoom = true;
  46910. }
  46911. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46912. var _this = this;
  46913. if (this._onCanvasBlurObserver) {
  46914. return;
  46915. }
  46916. this._scene = this.camera.getScene();
  46917. this._engine = this._scene.getEngine();
  46918. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46919. _this._keys = [];
  46920. });
  46921. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46922. var evt = info.event;
  46923. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46924. _this._ctrlPressed = evt.ctrlKey;
  46925. _this._altPressed = evt.altKey;
  46926. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46927. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46928. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46929. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46930. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46931. var index = _this._keys.indexOf(evt.keyCode);
  46932. if (index === -1) {
  46933. _this._keys.push(evt.keyCode);
  46934. }
  46935. if (evt.preventDefault) {
  46936. if (!noPreventDefault) {
  46937. evt.preventDefault();
  46938. }
  46939. }
  46940. }
  46941. }
  46942. else {
  46943. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46944. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46945. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46946. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46947. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46948. var index = _this._keys.indexOf(evt.keyCode);
  46949. if (index >= 0) {
  46950. _this._keys.splice(index, 1);
  46951. }
  46952. if (evt.preventDefault) {
  46953. if (!noPreventDefault) {
  46954. evt.preventDefault();
  46955. }
  46956. }
  46957. }
  46958. }
  46959. });
  46960. };
  46961. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46962. if (this._scene) {
  46963. if (this._onKeyboardObserver) {
  46964. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46965. }
  46966. if (this._onCanvasBlurObserver) {
  46967. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46968. }
  46969. this._onKeyboardObserver = null;
  46970. this._onCanvasBlurObserver = null;
  46971. }
  46972. this._keys = [];
  46973. };
  46974. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46975. if (this._onKeyboardObserver) {
  46976. var camera = this.camera;
  46977. for (var index = 0; index < this._keys.length; index++) {
  46978. var keyCode = this._keys[index];
  46979. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46980. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46981. camera.inertialPanningX -= 1 / this.panningSensibility;
  46982. }
  46983. else {
  46984. camera.inertialAlphaOffset -= 0.01;
  46985. }
  46986. }
  46987. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46988. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46989. camera.inertialPanningY += 1 / this.panningSensibility;
  46990. }
  46991. else if (this._altPressed && this.useAltToZoom) {
  46992. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46993. }
  46994. else {
  46995. camera.inertialBetaOffset -= 0.01;
  46996. }
  46997. }
  46998. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46999. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47000. camera.inertialPanningX += 1 / this.panningSensibility;
  47001. }
  47002. else {
  47003. camera.inertialAlphaOffset += 0.01;
  47004. }
  47005. }
  47006. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47007. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47008. camera.inertialPanningY -= 1 / this.panningSensibility;
  47009. }
  47010. else if (this._altPressed && this.useAltToZoom) {
  47011. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47012. }
  47013. else {
  47014. camera.inertialBetaOffset += 0.01;
  47015. }
  47016. }
  47017. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47018. camera.restoreState();
  47019. }
  47020. }
  47021. }
  47022. };
  47023. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47024. return "ArcRotateCameraKeyboardMoveInput";
  47025. };
  47026. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47027. return "keyboard";
  47028. };
  47029. __decorate([
  47030. BABYLON.serialize()
  47031. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47032. __decorate([
  47033. BABYLON.serialize()
  47034. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47035. __decorate([
  47036. BABYLON.serialize()
  47037. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47038. __decorate([
  47039. BABYLON.serialize()
  47040. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47041. __decorate([
  47042. BABYLON.serialize()
  47043. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47044. __decorate([
  47045. BABYLON.serialize()
  47046. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47047. __decorate([
  47048. BABYLON.serialize()
  47049. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47050. __decorate([
  47051. BABYLON.serialize()
  47052. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47053. return ArcRotateCameraKeyboardMoveInput;
  47054. }());
  47055. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47056. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47057. })(BABYLON || (BABYLON = {}));
  47058. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47059. "use strict";
  47060. var BABYLON;
  47061. (function (BABYLON) {
  47062. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47063. function ArcRotateCameraMouseWheelInput() {
  47064. this.wheelPrecision = 3.0;
  47065. /**
  47066. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47067. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47068. */
  47069. this.wheelDeltaPercentage = 0;
  47070. }
  47071. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47072. var _this = this;
  47073. this._wheel = function (p, s) {
  47074. //sanity check - this should be a PointerWheel event.
  47075. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47076. return;
  47077. var event = p.event;
  47078. var delta = 0;
  47079. if (event.wheelDelta) {
  47080. if (_this.wheelDeltaPercentage) {
  47081. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47082. if (event.wheelDelta > 0) {
  47083. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47084. }
  47085. else {
  47086. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47087. }
  47088. }
  47089. else {
  47090. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47091. }
  47092. }
  47093. else if (event.detail) {
  47094. delta = -event.detail / _this.wheelPrecision;
  47095. }
  47096. if (delta)
  47097. _this.camera.inertialRadiusOffset += delta;
  47098. if (event.preventDefault) {
  47099. if (!noPreventDefault) {
  47100. event.preventDefault();
  47101. }
  47102. }
  47103. };
  47104. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47105. };
  47106. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47107. if (this._observer && element) {
  47108. this.camera.getScene().onPointerObservable.remove(this._observer);
  47109. this._observer = null;
  47110. this._wheel = null;
  47111. }
  47112. };
  47113. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47114. return "ArcRotateCameraMouseWheelInput";
  47115. };
  47116. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47117. return "mousewheel";
  47118. };
  47119. __decorate([
  47120. BABYLON.serialize()
  47121. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47122. __decorate([
  47123. BABYLON.serialize()
  47124. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47125. return ArcRotateCameraMouseWheelInput;
  47126. }());
  47127. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47128. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47129. })(BABYLON || (BABYLON = {}));
  47130. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47131. "use strict";
  47132. var BABYLON;
  47133. (function (BABYLON) {
  47134. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47135. function ArcRotateCameraPointersInput() {
  47136. this.buttons = [0, 1, 2];
  47137. this.angularSensibilityX = 1000.0;
  47138. this.angularSensibilityY = 1000.0;
  47139. this.pinchPrecision = 12.0;
  47140. /**
  47141. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47142. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47143. */
  47144. this.pinchDeltaPercentage = 0;
  47145. this.panningSensibility = 1000.0;
  47146. this.multiTouchPanning = true;
  47147. this.multiTouchPanAndZoom = true;
  47148. this._isPanClick = false;
  47149. this.pinchInwards = true;
  47150. }
  47151. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47152. var _this = this;
  47153. var engine = this.camera.getEngine();
  47154. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47155. var pointA = null;
  47156. var pointB = null;
  47157. var previousPinchSquaredDistance = 0;
  47158. var initialDistance = 0;
  47159. var twoFingerActivityCount = 0;
  47160. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47161. this._pointerInput = function (p, s) {
  47162. var evt = p.event;
  47163. var isTouch = p.event.pointerType === "touch";
  47164. if (engine.isInVRExclusivePointerMode) {
  47165. return;
  47166. }
  47167. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47168. return;
  47169. }
  47170. var srcElement = (evt.srcElement || evt.target);
  47171. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47172. try {
  47173. srcElement.setPointerCapture(evt.pointerId);
  47174. }
  47175. catch (e) {
  47176. //Nothing to do with the error. Execution will continue.
  47177. }
  47178. // Manage panning with pan button click
  47179. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47180. // manage pointers
  47181. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47182. if (pointA === null) {
  47183. pointA = cacheSoloPointer;
  47184. }
  47185. else if (pointB === null) {
  47186. pointB = cacheSoloPointer;
  47187. }
  47188. if (!noPreventDefault) {
  47189. evt.preventDefault();
  47190. element.focus();
  47191. }
  47192. }
  47193. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47194. _this.camera.restoreState();
  47195. }
  47196. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47197. try {
  47198. srcElement.releasePointerCapture(evt.pointerId);
  47199. }
  47200. catch (e) {
  47201. //Nothing to do with the error.
  47202. }
  47203. cacheSoloPointer = null;
  47204. previousPinchSquaredDistance = 0;
  47205. previousMultiTouchPanPosition.isPaning = false;
  47206. previousMultiTouchPanPosition.isPinching = false;
  47207. twoFingerActivityCount = 0;
  47208. initialDistance = 0;
  47209. if (!isTouch) {
  47210. pointB = null; // Mouse and pen are mono pointer
  47211. }
  47212. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47213. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47214. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47215. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47216. if (engine._badOS) {
  47217. pointA = pointB = null;
  47218. }
  47219. else {
  47220. //only remove the impacted pointer in case of multitouch allowing on most
  47221. //platforms switching from rotate to zoom and pan seamlessly.
  47222. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47223. pointA = pointB;
  47224. pointB = null;
  47225. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47226. }
  47227. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47228. pointB = null;
  47229. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47230. }
  47231. else {
  47232. pointA = pointB = null;
  47233. }
  47234. }
  47235. if (!noPreventDefault) {
  47236. evt.preventDefault();
  47237. }
  47238. }
  47239. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47240. if (!noPreventDefault) {
  47241. evt.preventDefault();
  47242. }
  47243. // One button down
  47244. if (pointA && pointB === null && cacheSoloPointer) {
  47245. if (_this.panningSensibility !== 0 &&
  47246. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47247. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47248. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47249. }
  47250. else {
  47251. var offsetX = evt.clientX - cacheSoloPointer.x;
  47252. var offsetY = evt.clientY - cacheSoloPointer.y;
  47253. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47254. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47255. }
  47256. cacheSoloPointer.x = evt.clientX;
  47257. cacheSoloPointer.y = evt.clientY;
  47258. }
  47259. else if (pointA && pointB) {
  47260. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47261. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47262. ed.x = evt.clientX;
  47263. ed.y = evt.clientY;
  47264. var direction = _this.pinchInwards ? 1 : -1;
  47265. var distX = pointA.x - pointB.x;
  47266. var distY = pointA.y - pointB.y;
  47267. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47268. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47269. if (previousPinchSquaredDistance === 0) {
  47270. initialDistance = pinchDistance;
  47271. previousPinchSquaredDistance = pinchSquaredDistance;
  47272. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47273. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47274. return;
  47275. }
  47276. if (_this.multiTouchPanAndZoom) {
  47277. if (_this.pinchDeltaPercentage) {
  47278. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47279. }
  47280. else {
  47281. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47282. (_this.pinchPrecision *
  47283. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47284. direction);
  47285. }
  47286. if (_this.panningSensibility !== 0) {
  47287. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47288. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47289. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47290. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47291. previousMultiTouchPanPosition.x = pointersCenterX;
  47292. previousMultiTouchPanPosition.y = pointersCenterY;
  47293. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47294. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47295. }
  47296. }
  47297. else {
  47298. twoFingerActivityCount++;
  47299. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47300. if (_this.pinchDeltaPercentage) {
  47301. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47302. }
  47303. else {
  47304. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47305. (_this.pinchPrecision *
  47306. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47307. direction);
  47308. }
  47309. previousMultiTouchPanPosition.isPaning = false;
  47310. previousMultiTouchPanPosition.isPinching = true;
  47311. }
  47312. else {
  47313. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47314. if (!previousMultiTouchPanPosition.isPaning) {
  47315. previousMultiTouchPanPosition.isPaning = true;
  47316. previousMultiTouchPanPosition.isPinching = false;
  47317. previousMultiTouchPanPosition.x = ed.x;
  47318. previousMultiTouchPanPosition.y = ed.y;
  47319. return;
  47320. }
  47321. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47322. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47323. }
  47324. }
  47325. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47326. previousMultiTouchPanPosition.x = ed.x;
  47327. previousMultiTouchPanPosition.y = ed.y;
  47328. }
  47329. }
  47330. previousPinchSquaredDistance = pinchSquaredDistance;
  47331. }
  47332. }
  47333. };
  47334. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47335. this._onContextMenu = function (evt) {
  47336. evt.preventDefault();
  47337. };
  47338. if (!this.camera._useCtrlForPanning) {
  47339. element.addEventListener("contextmenu", this._onContextMenu, false);
  47340. }
  47341. this._onLostFocus = function () {
  47342. //this._keys = [];
  47343. pointA = pointB = null;
  47344. previousPinchSquaredDistance = 0;
  47345. previousMultiTouchPanPosition.isPaning = false;
  47346. previousMultiTouchPanPosition.isPinching = false;
  47347. twoFingerActivityCount = 0;
  47348. cacheSoloPointer = null;
  47349. initialDistance = 0;
  47350. };
  47351. this._onMouseMove = function (evt) {
  47352. if (!engine.isPointerLock) {
  47353. return;
  47354. }
  47355. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47356. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47357. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47358. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47359. if (!noPreventDefault) {
  47360. evt.preventDefault();
  47361. }
  47362. };
  47363. this._onGestureStart = function (e) {
  47364. if (window.MSGesture === undefined) {
  47365. return;
  47366. }
  47367. if (!_this._MSGestureHandler) {
  47368. _this._MSGestureHandler = new MSGesture();
  47369. _this._MSGestureHandler.target = element;
  47370. }
  47371. _this._MSGestureHandler.addPointer(e.pointerId);
  47372. };
  47373. this._onGesture = function (e) {
  47374. _this.camera.radius *= e.scale;
  47375. if (e.preventDefault) {
  47376. if (!noPreventDefault) {
  47377. e.stopPropagation();
  47378. e.preventDefault();
  47379. }
  47380. }
  47381. };
  47382. element.addEventListener("mousemove", this._onMouseMove, false);
  47383. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47384. element.addEventListener("MSGestureChange", this._onGesture, false);
  47385. BABYLON.Tools.RegisterTopRootEvents([
  47386. { name: "blur", handler: this._onLostFocus }
  47387. ]);
  47388. };
  47389. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47390. if (this._onLostFocus) {
  47391. BABYLON.Tools.UnregisterTopRootEvents([
  47392. { name: "blur", handler: this._onLostFocus }
  47393. ]);
  47394. }
  47395. if (element && this._observer) {
  47396. this.camera.getScene().onPointerObservable.remove(this._observer);
  47397. this._observer = null;
  47398. if (this._onContextMenu) {
  47399. element.removeEventListener("contextmenu", this._onContextMenu);
  47400. }
  47401. if (this._onMouseMove) {
  47402. element.removeEventListener("mousemove", this._onMouseMove);
  47403. }
  47404. if (this._onGestureStart) {
  47405. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47406. }
  47407. if (this._onGesture) {
  47408. element.removeEventListener("MSGestureChange", this._onGesture);
  47409. }
  47410. this._isPanClick = false;
  47411. this.pinchInwards = true;
  47412. this._onMouseMove = null;
  47413. this._onGestureStart = null;
  47414. this._onGesture = null;
  47415. this._MSGestureHandler = null;
  47416. this._onLostFocus = null;
  47417. this._onContextMenu = null;
  47418. }
  47419. };
  47420. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47421. return "ArcRotateCameraPointersInput";
  47422. };
  47423. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47424. return "pointers";
  47425. };
  47426. __decorate([
  47427. BABYLON.serialize()
  47428. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47429. __decorate([
  47430. BABYLON.serialize()
  47431. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47432. __decorate([
  47433. BABYLON.serialize()
  47434. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47435. __decorate([
  47436. BABYLON.serialize()
  47437. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47438. __decorate([
  47439. BABYLON.serialize()
  47440. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47441. __decorate([
  47442. BABYLON.serialize()
  47443. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47444. __decorate([
  47445. BABYLON.serialize()
  47446. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47447. __decorate([
  47448. BABYLON.serialize()
  47449. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47450. return ArcRotateCameraPointersInput;
  47451. }());
  47452. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47453. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47454. })(BABYLON || (BABYLON = {}));
  47455. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47456. "use strict";
  47457. var BABYLON;
  47458. (function (BABYLON) {
  47459. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47460. __extends(ArcRotateCameraInputsManager, _super);
  47461. function ArcRotateCameraInputsManager(camera) {
  47462. return _super.call(this, camera) || this;
  47463. }
  47464. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47465. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47466. return this;
  47467. };
  47468. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47469. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47470. return this;
  47471. };
  47472. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47473. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47474. return this;
  47475. };
  47476. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47477. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47478. return this;
  47479. };
  47480. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47481. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47482. return this;
  47483. };
  47484. return ArcRotateCameraInputsManager;
  47485. }(BABYLON.CameraInputsManager));
  47486. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47487. })(BABYLON || (BABYLON = {}));
  47488. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47489. "use strict";
  47490. var BABYLON;
  47491. (function (BABYLON) {
  47492. var ArcRotateCamera = /** @class */ (function (_super) {
  47493. __extends(ArcRotateCamera, _super);
  47494. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  47495. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  47496. _this.inertialAlphaOffset = 0;
  47497. _this.inertialBetaOffset = 0;
  47498. _this.inertialRadiusOffset = 0;
  47499. _this.lowerAlphaLimit = null;
  47500. _this.upperAlphaLimit = null;
  47501. _this.lowerBetaLimit = 0.01;
  47502. _this.upperBetaLimit = Math.PI;
  47503. _this.lowerRadiusLimit = null;
  47504. _this.upperRadiusLimit = null;
  47505. _this.inertialPanningX = 0;
  47506. _this.inertialPanningY = 0;
  47507. _this.pinchToPanMaxDistance = 20;
  47508. _this.panningDistanceLimit = null;
  47509. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47510. _this.panningInertia = 0.9;
  47511. //-- end properties for backward compatibility for inputs
  47512. _this.zoomOnFactor = 1;
  47513. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47514. _this.allowUpsideDown = true;
  47515. _this._viewMatrix = new BABYLON.Matrix();
  47516. // Panning
  47517. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47518. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47519. _this.checkCollisions = false;
  47520. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47521. _this._previousPosition = BABYLON.Vector3.Zero();
  47522. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47523. _this._newPosition = BABYLON.Vector3.Zero();
  47524. _this._computationVector = BABYLON.Vector3.Zero();
  47525. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47526. if (collidedMesh === void 0) { collidedMesh = null; }
  47527. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47528. newPosition.multiplyInPlace(_this._collider._radius);
  47529. }
  47530. if (!collidedMesh) {
  47531. _this._previousPosition.copyFrom(_this.position);
  47532. }
  47533. else {
  47534. _this.setPosition(newPosition);
  47535. if (_this.onCollide) {
  47536. _this.onCollide(collidedMesh);
  47537. }
  47538. }
  47539. // Recompute because of constraints
  47540. var cosa = Math.cos(_this.alpha);
  47541. var sina = Math.sin(_this.alpha);
  47542. var cosb = Math.cos(_this.beta);
  47543. var sinb = Math.sin(_this.beta);
  47544. if (sinb === 0) {
  47545. sinb = 0.0001;
  47546. }
  47547. var target = _this._getTargetPosition();
  47548. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47549. target.addToRef(_this._computationVector, _this._newPosition);
  47550. _this.position.copyFrom(_this._newPosition);
  47551. var up = _this.upVector;
  47552. if (_this.allowUpsideDown && _this.beta < 0) {
  47553. up = up.clone();
  47554. up = up.negate();
  47555. }
  47556. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  47557. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47558. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47559. _this._collisionTriggered = false;
  47560. };
  47561. _this._target = BABYLON.Vector3.Zero();
  47562. if (target) {
  47563. _this.setTarget(target);
  47564. }
  47565. _this.alpha = alpha;
  47566. _this.beta = beta;
  47567. _this.radius = radius;
  47568. _this.getViewMatrix();
  47569. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47570. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47571. return _this;
  47572. }
  47573. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47574. get: function () {
  47575. return this._target;
  47576. },
  47577. set: function (value) {
  47578. this.setTarget(value);
  47579. },
  47580. enumerable: true,
  47581. configurable: true
  47582. });
  47583. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47584. //-- begin properties for backward compatibility for inputs
  47585. get: function () {
  47586. var pointers = this.inputs.attached["pointers"];
  47587. if (pointers)
  47588. return pointers.angularSensibilityX;
  47589. return 0;
  47590. },
  47591. set: function (value) {
  47592. var pointers = this.inputs.attached["pointers"];
  47593. if (pointers) {
  47594. pointers.angularSensibilityX = value;
  47595. }
  47596. },
  47597. enumerable: true,
  47598. configurable: true
  47599. });
  47600. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47601. get: function () {
  47602. var pointers = this.inputs.attached["pointers"];
  47603. if (pointers)
  47604. return pointers.angularSensibilityY;
  47605. return 0;
  47606. },
  47607. set: function (value) {
  47608. var pointers = this.inputs.attached["pointers"];
  47609. if (pointers) {
  47610. pointers.angularSensibilityY = value;
  47611. }
  47612. },
  47613. enumerable: true,
  47614. configurable: true
  47615. });
  47616. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47617. get: function () {
  47618. var pointers = this.inputs.attached["pointers"];
  47619. if (pointers)
  47620. return pointers.pinchPrecision;
  47621. return 0;
  47622. },
  47623. set: function (value) {
  47624. var pointers = this.inputs.attached["pointers"];
  47625. if (pointers) {
  47626. pointers.pinchPrecision = value;
  47627. }
  47628. },
  47629. enumerable: true,
  47630. configurable: true
  47631. });
  47632. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47633. get: function () {
  47634. var pointers = this.inputs.attached["pointers"];
  47635. if (pointers)
  47636. return pointers.pinchDeltaPercentage;
  47637. return 0;
  47638. },
  47639. set: function (value) {
  47640. var pointers = this.inputs.attached["pointers"];
  47641. if (pointers) {
  47642. pointers.pinchDeltaPercentage = value;
  47643. }
  47644. },
  47645. enumerable: true,
  47646. configurable: true
  47647. });
  47648. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47649. get: function () {
  47650. var pointers = this.inputs.attached["pointers"];
  47651. if (pointers)
  47652. return pointers.panningSensibility;
  47653. return 0;
  47654. },
  47655. set: function (value) {
  47656. var pointers = this.inputs.attached["pointers"];
  47657. if (pointers) {
  47658. pointers.panningSensibility = value;
  47659. }
  47660. },
  47661. enumerable: true,
  47662. configurable: true
  47663. });
  47664. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47665. get: function () {
  47666. var keyboard = this.inputs.attached["keyboard"];
  47667. if (keyboard)
  47668. return keyboard.keysUp;
  47669. return [];
  47670. },
  47671. set: function (value) {
  47672. var keyboard = this.inputs.attached["keyboard"];
  47673. if (keyboard)
  47674. keyboard.keysUp = value;
  47675. },
  47676. enumerable: true,
  47677. configurable: true
  47678. });
  47679. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47680. get: function () {
  47681. var keyboard = this.inputs.attached["keyboard"];
  47682. if (keyboard)
  47683. return keyboard.keysDown;
  47684. return [];
  47685. },
  47686. set: function (value) {
  47687. var keyboard = this.inputs.attached["keyboard"];
  47688. if (keyboard)
  47689. keyboard.keysDown = value;
  47690. },
  47691. enumerable: true,
  47692. configurable: true
  47693. });
  47694. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47695. get: function () {
  47696. var keyboard = this.inputs.attached["keyboard"];
  47697. if (keyboard)
  47698. return keyboard.keysLeft;
  47699. return [];
  47700. },
  47701. set: function (value) {
  47702. var keyboard = this.inputs.attached["keyboard"];
  47703. if (keyboard)
  47704. keyboard.keysLeft = value;
  47705. },
  47706. enumerable: true,
  47707. configurable: true
  47708. });
  47709. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47710. get: function () {
  47711. var keyboard = this.inputs.attached["keyboard"];
  47712. if (keyboard)
  47713. return keyboard.keysRight;
  47714. return [];
  47715. },
  47716. set: function (value) {
  47717. var keyboard = this.inputs.attached["keyboard"];
  47718. if (keyboard)
  47719. keyboard.keysRight = value;
  47720. },
  47721. enumerable: true,
  47722. configurable: true
  47723. });
  47724. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47725. get: function () {
  47726. var mousewheel = this.inputs.attached["mousewheel"];
  47727. if (mousewheel)
  47728. return mousewheel.wheelPrecision;
  47729. return 0;
  47730. },
  47731. set: function (value) {
  47732. var mousewheel = this.inputs.attached["mousewheel"];
  47733. if (mousewheel)
  47734. mousewheel.wheelPrecision = value;
  47735. },
  47736. enumerable: true,
  47737. configurable: true
  47738. });
  47739. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47740. get: function () {
  47741. var mousewheel = this.inputs.attached["mousewheel"];
  47742. if (mousewheel)
  47743. return mousewheel.wheelDeltaPercentage;
  47744. return 0;
  47745. },
  47746. set: function (value) {
  47747. var mousewheel = this.inputs.attached["mousewheel"];
  47748. if (mousewheel)
  47749. mousewheel.wheelDeltaPercentage = value;
  47750. },
  47751. enumerable: true,
  47752. configurable: true
  47753. });
  47754. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47755. get: function () {
  47756. return this._bouncingBehavior;
  47757. },
  47758. enumerable: true,
  47759. configurable: true
  47760. });
  47761. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47762. get: function () {
  47763. return this._bouncingBehavior != null;
  47764. },
  47765. set: function (value) {
  47766. if (value === this.useBouncingBehavior) {
  47767. return;
  47768. }
  47769. if (value) {
  47770. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47771. this.addBehavior(this._bouncingBehavior);
  47772. }
  47773. else if (this._bouncingBehavior) {
  47774. this.removeBehavior(this._bouncingBehavior);
  47775. this._bouncingBehavior = null;
  47776. }
  47777. },
  47778. enumerable: true,
  47779. configurable: true
  47780. });
  47781. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47782. get: function () {
  47783. return this._framingBehavior;
  47784. },
  47785. enumerable: true,
  47786. configurable: true
  47787. });
  47788. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47789. get: function () {
  47790. return this._framingBehavior != null;
  47791. },
  47792. set: function (value) {
  47793. if (value === this.useFramingBehavior) {
  47794. return;
  47795. }
  47796. if (value) {
  47797. this._framingBehavior = new BABYLON.FramingBehavior();
  47798. this.addBehavior(this._framingBehavior);
  47799. }
  47800. else if (this._framingBehavior) {
  47801. this.removeBehavior(this._framingBehavior);
  47802. this._framingBehavior = null;
  47803. }
  47804. },
  47805. enumerable: true,
  47806. configurable: true
  47807. });
  47808. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47809. get: function () {
  47810. return this._autoRotationBehavior;
  47811. },
  47812. enumerable: true,
  47813. configurable: true
  47814. });
  47815. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47816. get: function () {
  47817. return this._autoRotationBehavior != null;
  47818. },
  47819. set: function (value) {
  47820. if (value === this.useAutoRotationBehavior) {
  47821. return;
  47822. }
  47823. if (value) {
  47824. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47825. this.addBehavior(this._autoRotationBehavior);
  47826. }
  47827. else if (this._autoRotationBehavior) {
  47828. this.removeBehavior(this._autoRotationBehavior);
  47829. this._autoRotationBehavior = null;
  47830. }
  47831. },
  47832. enumerable: true,
  47833. configurable: true
  47834. });
  47835. // Cache
  47836. ArcRotateCamera.prototype._initCache = function () {
  47837. _super.prototype._initCache.call(this);
  47838. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47839. this._cache.alpha = undefined;
  47840. this._cache.beta = undefined;
  47841. this._cache.radius = undefined;
  47842. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47843. };
  47844. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47845. if (!ignoreParentClass) {
  47846. _super.prototype._updateCache.call(this);
  47847. }
  47848. this._cache._target.copyFrom(this._getTargetPosition());
  47849. this._cache.alpha = this.alpha;
  47850. this._cache.beta = this.beta;
  47851. this._cache.radius = this.radius;
  47852. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47853. };
  47854. ArcRotateCamera.prototype._getTargetPosition = function () {
  47855. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47856. var pos = this._targetHost.getAbsolutePosition();
  47857. if (this._targetBoundingCenter) {
  47858. pos.addToRef(this._targetBoundingCenter, this._target);
  47859. }
  47860. else {
  47861. this._target.copyFrom(pos);
  47862. }
  47863. }
  47864. var lockedTargetPosition = this._getLockedTargetPosition();
  47865. if (lockedTargetPosition) {
  47866. return lockedTargetPosition;
  47867. }
  47868. return this._target;
  47869. };
  47870. ArcRotateCamera.prototype.storeState = function () {
  47871. this._storedAlpha = this.alpha;
  47872. this._storedBeta = this.beta;
  47873. this._storedRadius = this.radius;
  47874. this._storedTarget = this._getTargetPosition().clone();
  47875. return _super.prototype.storeState.call(this);
  47876. };
  47877. /**
  47878. * Restored camera state. You must call storeState() first
  47879. */
  47880. ArcRotateCamera.prototype._restoreStateValues = function () {
  47881. if (!_super.prototype._restoreStateValues.call(this)) {
  47882. return false;
  47883. }
  47884. this.alpha = this._storedAlpha;
  47885. this.beta = this._storedBeta;
  47886. this.radius = this._storedRadius;
  47887. this.setTarget(this._storedTarget.clone());
  47888. this.inertialAlphaOffset = 0;
  47889. this.inertialBetaOffset = 0;
  47890. this.inertialRadiusOffset = 0;
  47891. this.inertialPanningX = 0;
  47892. this.inertialPanningY = 0;
  47893. return true;
  47894. };
  47895. // Synchronized
  47896. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47897. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47898. return false;
  47899. return this._cache._target.equals(this._getTargetPosition())
  47900. && this._cache.alpha === this.alpha
  47901. && this._cache.beta === this.beta
  47902. && this._cache.radius === this.radius
  47903. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47904. };
  47905. // Methods
  47906. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47907. var _this = this;
  47908. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47909. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47910. this._useCtrlForPanning = useCtrlForPanning;
  47911. this._panningMouseButton = panningMouseButton;
  47912. this.inputs.attachElement(element, noPreventDefault);
  47913. this._reset = function () {
  47914. _this.inertialAlphaOffset = 0;
  47915. _this.inertialBetaOffset = 0;
  47916. _this.inertialRadiusOffset = 0;
  47917. _this.inertialPanningX = 0;
  47918. _this.inertialPanningY = 0;
  47919. };
  47920. };
  47921. ArcRotateCamera.prototype.detachControl = function (element) {
  47922. this.inputs.detachElement(element);
  47923. if (this._reset) {
  47924. this._reset();
  47925. }
  47926. };
  47927. ArcRotateCamera.prototype._checkInputs = function () {
  47928. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47929. if (this._collisionTriggered) {
  47930. return;
  47931. }
  47932. this.inputs.checkInputs();
  47933. // Inertia
  47934. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47935. if (this.getScene().useRightHandedSystem) {
  47936. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  47937. }
  47938. else {
  47939. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  47940. }
  47941. this.beta += this.inertialBetaOffset;
  47942. this.radius -= this.inertialRadiusOffset;
  47943. this.inertialAlphaOffset *= this.inertia;
  47944. this.inertialBetaOffset *= this.inertia;
  47945. this.inertialRadiusOffset *= this.inertia;
  47946. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47947. this.inertialAlphaOffset = 0;
  47948. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47949. this.inertialBetaOffset = 0;
  47950. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47951. this.inertialRadiusOffset = 0;
  47952. }
  47953. // Panning inertia
  47954. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47955. if (!this._localDirection) {
  47956. this._localDirection = BABYLON.Vector3.Zero();
  47957. this._transformedDirection = BABYLON.Vector3.Zero();
  47958. }
  47959. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47960. this._localDirection.multiplyInPlace(this.panningAxis);
  47961. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47962. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47963. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47964. if (!this.panningAxis.y) {
  47965. this._transformedDirection.y = 0;
  47966. }
  47967. if (!this._targetHost) {
  47968. if (this.panningDistanceLimit) {
  47969. this._transformedDirection.addInPlace(this._target);
  47970. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47971. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47972. this._target.copyFrom(this._transformedDirection);
  47973. }
  47974. }
  47975. else {
  47976. this._target.addInPlace(this._transformedDirection);
  47977. }
  47978. }
  47979. this.inertialPanningX *= this.panningInertia;
  47980. this.inertialPanningY *= this.panningInertia;
  47981. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47982. this.inertialPanningX = 0;
  47983. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47984. this.inertialPanningY = 0;
  47985. }
  47986. // Limits
  47987. this._checkLimits();
  47988. _super.prototype._checkInputs.call(this);
  47989. };
  47990. ArcRotateCamera.prototype._checkLimits = function () {
  47991. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47992. if (this.allowUpsideDown && this.beta > Math.PI) {
  47993. this.beta = this.beta - (2 * Math.PI);
  47994. }
  47995. }
  47996. else {
  47997. if (this.beta < this.lowerBetaLimit) {
  47998. this.beta = this.lowerBetaLimit;
  47999. }
  48000. }
  48001. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48002. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48003. this.beta = this.beta + (2 * Math.PI);
  48004. }
  48005. }
  48006. else {
  48007. if (this.beta > this.upperBetaLimit) {
  48008. this.beta = this.upperBetaLimit;
  48009. }
  48010. }
  48011. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48012. this.alpha = this.lowerAlphaLimit;
  48013. }
  48014. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48015. this.alpha = this.upperAlphaLimit;
  48016. }
  48017. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48018. this.radius = this.lowerRadiusLimit;
  48019. }
  48020. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48021. this.radius = this.upperRadiusLimit;
  48022. }
  48023. };
  48024. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48025. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48026. this.radius = this._computationVector.length();
  48027. if (this.radius === 0) {
  48028. this.radius = 0.0001; // Just to avoid division by zero
  48029. }
  48030. // Alpha
  48031. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48032. if (this._computationVector.z < 0) {
  48033. this.alpha = 2 * Math.PI - this.alpha;
  48034. }
  48035. // Beta
  48036. this.beta = Math.acos(this._computationVector.y / this.radius);
  48037. this._checkLimits();
  48038. };
  48039. ArcRotateCamera.prototype.setPosition = function (position) {
  48040. if (this.position.equals(position)) {
  48041. return;
  48042. }
  48043. this.position.copyFrom(position);
  48044. this.rebuildAnglesAndRadius();
  48045. };
  48046. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48047. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48048. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48049. if (target.getBoundingInfo) {
  48050. if (toBoundingCenter) {
  48051. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48052. }
  48053. else {
  48054. this._targetBoundingCenter = null;
  48055. }
  48056. this._targetHost = target;
  48057. this._target = this._getTargetPosition();
  48058. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48059. }
  48060. else {
  48061. var newTarget = target;
  48062. var currentTarget = this._getTargetPosition();
  48063. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48064. return;
  48065. }
  48066. this._targetHost = null;
  48067. this._target = newTarget;
  48068. this._targetBoundingCenter = null;
  48069. this.onMeshTargetChangedObservable.notifyObservers(null);
  48070. }
  48071. this.rebuildAnglesAndRadius();
  48072. };
  48073. ArcRotateCamera.prototype._getViewMatrix = function () {
  48074. // Compute
  48075. var cosa = Math.cos(this.alpha);
  48076. var sina = Math.sin(this.alpha);
  48077. var cosb = Math.cos(this.beta);
  48078. var sinb = Math.sin(this.beta);
  48079. if (sinb === 0) {
  48080. sinb = 0.0001;
  48081. }
  48082. var target = this._getTargetPosition();
  48083. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48084. target.addToRef(this._computationVector, this._newPosition);
  48085. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48086. if (!this._collider) {
  48087. this._collider = new BABYLON.Collider();
  48088. }
  48089. this._collider._radius = this.collisionRadius;
  48090. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48091. this._collisionTriggered = true;
  48092. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48093. }
  48094. else {
  48095. this.position.copyFrom(this._newPosition);
  48096. var up = this.upVector;
  48097. if (this.allowUpsideDown && sinb < 0) {
  48098. up = up.clone();
  48099. up = up.negate();
  48100. }
  48101. if (this.getScene().useRightHandedSystem) {
  48102. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  48103. }
  48104. else {
  48105. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  48106. }
  48107. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48108. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48109. }
  48110. this._currentTarget = target;
  48111. return this._viewMatrix;
  48112. };
  48113. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48114. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48115. meshes = meshes || this.getScene().meshes;
  48116. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48117. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48118. this.radius = distance * this.zoomOnFactor;
  48119. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48120. };
  48121. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48122. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48123. var meshesOrMinMaxVector;
  48124. var distance;
  48125. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  48126. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48127. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48128. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48129. }
  48130. else {
  48131. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48132. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48133. distance = minMaxVectorAndDistance.distance;
  48134. }
  48135. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48136. if (!doNotUpdateMaxZ) {
  48137. this.maxZ = distance * 2;
  48138. }
  48139. };
  48140. /**
  48141. * @override
  48142. * Override Camera.createRigCamera
  48143. */
  48144. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48145. var alphaShift = 0;
  48146. switch (this.cameraRigMode) {
  48147. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48148. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48149. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48150. case BABYLON.Camera.RIG_MODE_VR:
  48151. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48152. break;
  48153. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48154. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48155. break;
  48156. }
  48157. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48158. rigCam._cameraRigParams = {};
  48159. return rigCam;
  48160. };
  48161. /**
  48162. * @override
  48163. * Override Camera._updateRigCameras
  48164. */
  48165. ArcRotateCamera.prototype._updateRigCameras = function () {
  48166. var camLeft = this._rigCameras[0];
  48167. var camRight = this._rigCameras[1];
  48168. camLeft.beta = camRight.beta = this.beta;
  48169. camLeft.radius = camRight.radius = this.radius;
  48170. switch (this.cameraRigMode) {
  48171. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48172. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48173. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48174. case BABYLON.Camera.RIG_MODE_VR:
  48175. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48176. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48177. break;
  48178. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48179. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48180. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48181. break;
  48182. }
  48183. _super.prototype._updateRigCameras.call(this);
  48184. };
  48185. ArcRotateCamera.prototype.dispose = function () {
  48186. this.inputs.clear();
  48187. _super.prototype.dispose.call(this);
  48188. };
  48189. ArcRotateCamera.prototype.getClassName = function () {
  48190. return "ArcRotateCamera";
  48191. };
  48192. __decorate([
  48193. BABYLON.serialize()
  48194. ], ArcRotateCamera.prototype, "alpha", void 0);
  48195. __decorate([
  48196. BABYLON.serialize()
  48197. ], ArcRotateCamera.prototype, "beta", void 0);
  48198. __decorate([
  48199. BABYLON.serialize()
  48200. ], ArcRotateCamera.prototype, "radius", void 0);
  48201. __decorate([
  48202. BABYLON.serializeAsVector3("target")
  48203. ], ArcRotateCamera.prototype, "_target", void 0);
  48204. __decorate([
  48205. BABYLON.serialize()
  48206. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48207. __decorate([
  48208. BABYLON.serialize()
  48209. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48210. __decorate([
  48211. BABYLON.serialize()
  48212. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48213. __decorate([
  48214. BABYLON.serialize()
  48215. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48216. __decorate([
  48217. BABYLON.serialize()
  48218. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48219. __decorate([
  48220. BABYLON.serialize()
  48221. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48222. __decorate([
  48223. BABYLON.serialize()
  48224. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48225. __decorate([
  48226. BABYLON.serialize()
  48227. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48228. __decorate([
  48229. BABYLON.serialize()
  48230. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48231. __decorate([
  48232. BABYLON.serialize()
  48233. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48234. __decorate([
  48235. BABYLON.serialize()
  48236. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48237. __decorate([
  48238. BABYLON.serialize()
  48239. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48240. __decorate([
  48241. BABYLON.serialize()
  48242. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48243. __decorate([
  48244. BABYLON.serializeAsVector3()
  48245. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48246. __decorate([
  48247. BABYLON.serialize()
  48248. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48249. __decorate([
  48250. BABYLON.serialize()
  48251. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48252. __decorate([
  48253. BABYLON.serialize()
  48254. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48255. return ArcRotateCamera;
  48256. }(BABYLON.TargetCamera));
  48257. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48258. })(BABYLON || (BABYLON = {}));
  48259. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48260. "use strict";
  48261. var BABYLON;
  48262. (function (BABYLON) {
  48263. /**
  48264. * The HemisphericLight simulates the ambient environment light,
  48265. * so the passed direction is the light reflection direction, not the incoming direction.
  48266. */
  48267. var HemisphericLight = /** @class */ (function (_super) {
  48268. __extends(HemisphericLight, _super);
  48269. /**
  48270. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48271. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48272. * The HemisphericLight can't cast shadows.
  48273. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48274. * @param name The friendly name of the light
  48275. * @param direction The direction of the light reflection
  48276. * @param scene The scene the light belongs to
  48277. */
  48278. function HemisphericLight(name, direction, scene) {
  48279. var _this = _super.call(this, name, scene) || this;
  48280. /**
  48281. * The groundColor is the light in the opposite direction to the one specified during creation.
  48282. * 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.
  48283. */
  48284. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48285. _this.direction = direction || BABYLON.Vector3.Up();
  48286. return _this;
  48287. }
  48288. HemisphericLight.prototype._buildUniformLayout = function () {
  48289. this._uniformBuffer.addUniform("vLightData", 4);
  48290. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48291. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48292. this._uniformBuffer.addUniform("vLightGround", 3);
  48293. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48294. this._uniformBuffer.addUniform("depthValues", 2);
  48295. this._uniformBuffer.create();
  48296. };
  48297. /**
  48298. * Returns the string "HemisphericLight".
  48299. * @return The class name
  48300. */
  48301. HemisphericLight.prototype.getClassName = function () {
  48302. return "HemisphericLight";
  48303. };
  48304. /**
  48305. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48306. * Returns the updated direction.
  48307. * @param target The target the direction should point to
  48308. * @return The computed direction
  48309. */
  48310. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48311. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48312. return this.direction;
  48313. };
  48314. /**
  48315. * Returns the shadow generator associated to the light.
  48316. * @returns Always null for hemispheric lights because it does not support shadows.
  48317. */
  48318. HemisphericLight.prototype.getShadowGenerator = function () {
  48319. return null;
  48320. };
  48321. /**
  48322. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48323. * @param effect The effect to update
  48324. * @param lightIndex The index of the light in the effect to update
  48325. * @returns The hemispheric light
  48326. */
  48327. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48328. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48329. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48330. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48331. return this;
  48332. };
  48333. /**
  48334. * @ignore internal use only.
  48335. */
  48336. HemisphericLight.prototype._getWorldMatrix = function () {
  48337. if (!this._worldMatrix) {
  48338. this._worldMatrix = BABYLON.Matrix.Identity();
  48339. }
  48340. return this._worldMatrix;
  48341. };
  48342. /**
  48343. * Returns the integer 3.
  48344. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48345. */
  48346. HemisphericLight.prototype.getTypeID = function () {
  48347. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48348. };
  48349. __decorate([
  48350. BABYLON.serializeAsColor3()
  48351. ], HemisphericLight.prototype, "groundColor", void 0);
  48352. __decorate([
  48353. BABYLON.serializeAsVector3()
  48354. ], HemisphericLight.prototype, "direction", void 0);
  48355. return HemisphericLight;
  48356. }(BABYLON.Light));
  48357. BABYLON.HemisphericLight = HemisphericLight;
  48358. })(BABYLON || (BABYLON = {}));
  48359. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48360. "use strict";
  48361. var BABYLON;
  48362. (function (BABYLON) {
  48363. /**
  48364. * Base implementation IShadowLight
  48365. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48366. */
  48367. var ShadowLight = /** @class */ (function (_super) {
  48368. __extends(ShadowLight, _super);
  48369. function ShadowLight() {
  48370. var _this = _super !== null && _super.apply(this, arguments) || this;
  48371. _this._needProjectionMatrixCompute = true;
  48372. return _this;
  48373. }
  48374. ShadowLight.prototype._setPosition = function (value) {
  48375. this._position = value;
  48376. };
  48377. Object.defineProperty(ShadowLight.prototype, "position", {
  48378. /**
  48379. * Sets the position the shadow will be casted from. Also use as the light position for both
  48380. * point and spot lights.
  48381. */
  48382. get: function () {
  48383. return this._position;
  48384. },
  48385. /**
  48386. * Sets the position the shadow will be casted from. Also use as the light position for both
  48387. * point and spot lights.
  48388. */
  48389. set: function (value) {
  48390. this._setPosition(value);
  48391. },
  48392. enumerable: true,
  48393. configurable: true
  48394. });
  48395. ShadowLight.prototype._setDirection = function (value) {
  48396. this._direction = value;
  48397. };
  48398. Object.defineProperty(ShadowLight.prototype, "direction", {
  48399. /**
  48400. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48401. * Also use as the light direction on spot and directional lights.
  48402. */
  48403. get: function () {
  48404. return this._direction;
  48405. },
  48406. /**
  48407. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48408. * Also use as the light direction on spot and directional lights.
  48409. */
  48410. set: function (value) {
  48411. this._setDirection(value);
  48412. },
  48413. enumerable: true,
  48414. configurable: true
  48415. });
  48416. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48417. /**
  48418. * Gets the shadow projection clipping minimum z value.
  48419. */
  48420. get: function () {
  48421. return this._shadowMinZ;
  48422. },
  48423. /**
  48424. * Sets the shadow projection clipping minimum z value.
  48425. */
  48426. set: function (value) {
  48427. this._shadowMinZ = value;
  48428. this.forceProjectionMatrixCompute();
  48429. },
  48430. enumerable: true,
  48431. configurable: true
  48432. });
  48433. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48434. /**
  48435. * Sets the shadow projection clipping maximum z value.
  48436. */
  48437. get: function () {
  48438. return this._shadowMaxZ;
  48439. },
  48440. /**
  48441. * Gets the shadow projection clipping maximum z value.
  48442. */
  48443. set: function (value) {
  48444. this._shadowMaxZ = value;
  48445. this.forceProjectionMatrixCompute();
  48446. },
  48447. enumerable: true,
  48448. configurable: true
  48449. });
  48450. /**
  48451. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48452. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48453. */
  48454. ShadowLight.prototype.computeTransformedInformation = function () {
  48455. if (this.parent && this.parent.getWorldMatrix) {
  48456. if (!this.transformedPosition) {
  48457. this.transformedPosition = BABYLON.Vector3.Zero();
  48458. }
  48459. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48460. // In case the direction is present.
  48461. if (this.direction) {
  48462. if (!this.transformedDirection) {
  48463. this.transformedDirection = BABYLON.Vector3.Zero();
  48464. }
  48465. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48466. }
  48467. return true;
  48468. }
  48469. return false;
  48470. };
  48471. /**
  48472. * Return the depth scale used for the shadow map.
  48473. * @returns the depth scale.
  48474. */
  48475. ShadowLight.prototype.getDepthScale = function () {
  48476. return 50.0;
  48477. };
  48478. /**
  48479. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48480. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48481. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48482. */
  48483. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48484. return this.transformedDirection ? this.transformedDirection : this.direction;
  48485. };
  48486. /**
  48487. * Returns the ShadowLight absolute position in the World.
  48488. * @returns the position vector in world space
  48489. */
  48490. ShadowLight.prototype.getAbsolutePosition = function () {
  48491. return this.transformedPosition ? this.transformedPosition : this.position;
  48492. };
  48493. /**
  48494. * Sets the ShadowLight direction toward the passed target.
  48495. * @param target The point tot target in local space
  48496. * @returns the updated ShadowLight direction
  48497. */
  48498. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48499. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48500. return this.direction;
  48501. };
  48502. /**
  48503. * Returns the light rotation in euler definition.
  48504. * @returns the x y z rotation in local space.
  48505. */
  48506. ShadowLight.prototype.getRotation = function () {
  48507. this.direction.normalize();
  48508. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48509. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48510. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48511. };
  48512. /**
  48513. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48514. * @returns true if a cube texture needs to be use
  48515. */
  48516. ShadowLight.prototype.needCube = function () {
  48517. return false;
  48518. };
  48519. /**
  48520. * Detects if the projection matrix requires to be recomputed this frame.
  48521. * @returns true if it requires to be recomputed otherwise, false.
  48522. */
  48523. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48524. return this._needProjectionMatrixCompute;
  48525. };
  48526. /**
  48527. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48528. */
  48529. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48530. this._needProjectionMatrixCompute = true;
  48531. };
  48532. /**
  48533. * Get the world matrix of the sahdow lights.
  48534. * @ignore Internal Use Only
  48535. */
  48536. ShadowLight.prototype._getWorldMatrix = function () {
  48537. if (!this._worldMatrix) {
  48538. this._worldMatrix = BABYLON.Matrix.Identity();
  48539. }
  48540. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48541. return this._worldMatrix;
  48542. };
  48543. /**
  48544. * Gets the minZ used for shadow according to both the scene and the light.
  48545. * @param activeCamera The camera we are returning the min for
  48546. * @returns the depth min z
  48547. */
  48548. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48549. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48550. };
  48551. /**
  48552. * Gets the maxZ used for shadow according to both the scene and the light.
  48553. * @param activeCamera The camera we are returning the max for
  48554. * @returns the depth max z
  48555. */
  48556. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48557. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48558. };
  48559. /**
  48560. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48561. * @param matrix The materix to updated with the projection information
  48562. * @param viewMatrix The transform matrix of the light
  48563. * @param renderList The list of mesh to render in the map
  48564. * @returns The current light
  48565. */
  48566. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48567. if (this.customProjectionMatrixBuilder) {
  48568. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48569. }
  48570. else {
  48571. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48572. }
  48573. return this;
  48574. };
  48575. __decorate([
  48576. BABYLON.serializeAsVector3()
  48577. ], ShadowLight.prototype, "position", null);
  48578. __decorate([
  48579. BABYLON.serializeAsVector3()
  48580. ], ShadowLight.prototype, "direction", null);
  48581. __decorate([
  48582. BABYLON.serialize()
  48583. ], ShadowLight.prototype, "shadowMinZ", null);
  48584. __decorate([
  48585. BABYLON.serialize()
  48586. ], ShadowLight.prototype, "shadowMaxZ", null);
  48587. return ShadowLight;
  48588. }(BABYLON.Light));
  48589. BABYLON.ShadowLight = ShadowLight;
  48590. })(BABYLON || (BABYLON = {}));
  48591. //# sourceMappingURL=babylon.shadowLight.js.map
  48592. "use strict";
  48593. var BABYLON;
  48594. (function (BABYLON) {
  48595. /**
  48596. * A point light is a light defined by an unique point in world space.
  48597. * The light is emitted in every direction from this point.
  48598. * A good example of a point light is a standard light bulb.
  48599. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48600. */
  48601. var PointLight = /** @class */ (function (_super) {
  48602. __extends(PointLight, _super);
  48603. /**
  48604. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48605. * A PointLight emits the light in every direction.
  48606. * It can cast shadows.
  48607. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48608. * ```javascript
  48609. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48610. * ```
  48611. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48612. * @param name The light friendly name
  48613. * @param position The position of the point light in the scene
  48614. * @param scene The scene the lights belongs to
  48615. */
  48616. function PointLight(name, position, scene) {
  48617. var _this = _super.call(this, name, scene) || this;
  48618. _this._shadowAngle = Math.PI / 2;
  48619. _this.position = position;
  48620. return _this;
  48621. }
  48622. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48623. /**
  48624. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48625. * This specifies what angle the shadow will use to be created.
  48626. *
  48627. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48628. */
  48629. get: function () {
  48630. return this._shadowAngle;
  48631. },
  48632. /**
  48633. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48634. * This specifies what angle the shadow will use to be created.
  48635. *
  48636. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48637. */
  48638. set: function (value) {
  48639. this._shadowAngle = value;
  48640. this.forceProjectionMatrixCompute();
  48641. },
  48642. enumerable: true,
  48643. configurable: true
  48644. });
  48645. Object.defineProperty(PointLight.prototype, "direction", {
  48646. /**
  48647. * Gets the direction if it has been set.
  48648. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48649. */
  48650. get: function () {
  48651. return this._direction;
  48652. },
  48653. /**
  48654. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48655. */
  48656. set: function (value) {
  48657. var previousNeedCube = this.needCube();
  48658. this._direction = value;
  48659. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48660. this._shadowGenerator.recreateShadowMap();
  48661. }
  48662. },
  48663. enumerable: true,
  48664. configurable: true
  48665. });
  48666. /**
  48667. * Returns the string "PointLight"
  48668. * @returns the class name
  48669. */
  48670. PointLight.prototype.getClassName = function () {
  48671. return "PointLight";
  48672. };
  48673. /**
  48674. * Returns the integer 0.
  48675. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48676. */
  48677. PointLight.prototype.getTypeID = function () {
  48678. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48679. };
  48680. /**
  48681. * Specifies wether or not the shadowmap should be a cube texture.
  48682. * @returns true if the shadowmap needs to be a cube texture.
  48683. */
  48684. PointLight.prototype.needCube = function () {
  48685. return !this.direction;
  48686. };
  48687. /**
  48688. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48689. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48690. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48691. */
  48692. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48693. if (this.direction) {
  48694. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48695. }
  48696. else {
  48697. switch (faceIndex) {
  48698. case 0:
  48699. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48700. case 1:
  48701. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48702. case 2:
  48703. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48704. case 3:
  48705. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48706. case 4:
  48707. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48708. case 5:
  48709. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48710. }
  48711. }
  48712. return BABYLON.Vector3.Zero();
  48713. };
  48714. /**
  48715. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48716. * - fov = PI / 2
  48717. * - aspect ratio : 1.0
  48718. * - z-near and far equal to the active camera minZ and maxZ.
  48719. * Returns the PointLight.
  48720. */
  48721. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48722. var activeCamera = this.getScene().activeCamera;
  48723. if (!activeCamera) {
  48724. return;
  48725. }
  48726. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48727. };
  48728. PointLight.prototype._buildUniformLayout = function () {
  48729. this._uniformBuffer.addUniform("vLightData", 4);
  48730. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48731. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48732. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48733. this._uniformBuffer.addUniform("depthValues", 2);
  48734. this._uniformBuffer.create();
  48735. };
  48736. /**
  48737. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48738. * @param effect The effect to update
  48739. * @param lightIndex The index of the light in the effect to update
  48740. * @returns The point light
  48741. */
  48742. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48743. if (this.computeTransformedInformation()) {
  48744. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48745. return this;
  48746. }
  48747. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48748. return this;
  48749. };
  48750. __decorate([
  48751. BABYLON.serialize()
  48752. ], PointLight.prototype, "shadowAngle", null);
  48753. return PointLight;
  48754. }(BABYLON.ShadowLight));
  48755. BABYLON.PointLight = PointLight;
  48756. })(BABYLON || (BABYLON = {}));
  48757. //# sourceMappingURL=babylon.pointLight.js.map
  48758. "use strict";
  48759. var BABYLON;
  48760. (function (BABYLON) {
  48761. /**
  48762. * A directional light is defined by a direction (what a surprise!).
  48763. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48764. * 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.
  48765. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48766. */
  48767. var DirectionalLight = /** @class */ (function (_super) {
  48768. __extends(DirectionalLight, _super);
  48769. /**
  48770. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48771. * The directional light is emitted from everywhere in the given direction.
  48772. * It can cast shawdows.
  48773. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48774. * @param name The friendly name of the light
  48775. * @param direction The direction of the light
  48776. * @param scene The scene the light belongs to
  48777. */
  48778. function DirectionalLight(name, direction, scene) {
  48779. var _this = _super.call(this, name, scene) || this;
  48780. _this._shadowFrustumSize = 0;
  48781. _this._shadowOrthoScale = 0.1;
  48782. /**
  48783. * Automatically compute the projection matrix to best fit (including all the casters)
  48784. * on each frame.
  48785. */
  48786. _this.autoUpdateExtends = true;
  48787. // Cache
  48788. _this._orthoLeft = Number.MAX_VALUE;
  48789. _this._orthoRight = Number.MIN_VALUE;
  48790. _this._orthoTop = Number.MIN_VALUE;
  48791. _this._orthoBottom = Number.MAX_VALUE;
  48792. _this.position = direction.scale(-1.0);
  48793. _this.direction = direction;
  48794. return _this;
  48795. }
  48796. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48797. /**
  48798. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48799. */
  48800. get: function () {
  48801. return this._shadowFrustumSize;
  48802. },
  48803. /**
  48804. * Specifies a fix frustum size for the shadow generation.
  48805. */
  48806. set: function (value) {
  48807. this._shadowFrustumSize = value;
  48808. this.forceProjectionMatrixCompute();
  48809. },
  48810. enumerable: true,
  48811. configurable: true
  48812. });
  48813. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48814. /**
  48815. * Gets the shadow projection scale against the optimal computed one.
  48816. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48817. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48818. */
  48819. get: function () {
  48820. return this._shadowOrthoScale;
  48821. },
  48822. /**
  48823. * Sets the shadow projection scale against the optimal computed one.
  48824. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48825. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48826. */
  48827. set: function (value) {
  48828. this._shadowOrthoScale = value;
  48829. this.forceProjectionMatrixCompute();
  48830. },
  48831. enumerable: true,
  48832. configurable: true
  48833. });
  48834. /**
  48835. * Returns the string "DirectionalLight".
  48836. * @return The class name
  48837. */
  48838. DirectionalLight.prototype.getClassName = function () {
  48839. return "DirectionalLight";
  48840. };
  48841. /**
  48842. * Returns the integer 1.
  48843. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48844. */
  48845. DirectionalLight.prototype.getTypeID = function () {
  48846. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48847. };
  48848. /**
  48849. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48850. * Returns the DirectionalLight Shadow projection matrix.
  48851. */
  48852. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48853. if (this.shadowFrustumSize > 0) {
  48854. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48855. }
  48856. else {
  48857. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48858. }
  48859. };
  48860. /**
  48861. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48862. * Returns the DirectionalLight Shadow projection matrix.
  48863. */
  48864. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48865. var activeCamera = this.getScene().activeCamera;
  48866. if (!activeCamera) {
  48867. return;
  48868. }
  48869. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48870. };
  48871. /**
  48872. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48873. * Returns the DirectionalLight Shadow projection matrix.
  48874. */
  48875. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48876. var activeCamera = this.getScene().activeCamera;
  48877. if (!activeCamera) {
  48878. return;
  48879. }
  48880. // Check extends
  48881. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48882. var tempVector3 = BABYLON.Vector3.Zero();
  48883. this._orthoLeft = Number.MAX_VALUE;
  48884. this._orthoRight = Number.MIN_VALUE;
  48885. this._orthoTop = Number.MIN_VALUE;
  48886. this._orthoBottom = Number.MAX_VALUE;
  48887. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48888. var mesh = renderList[meshIndex];
  48889. if (!mesh) {
  48890. continue;
  48891. }
  48892. var boundingInfo = mesh.getBoundingInfo();
  48893. var boundingBox = boundingInfo.boundingBox;
  48894. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48895. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48896. if (tempVector3.x < this._orthoLeft)
  48897. this._orthoLeft = tempVector3.x;
  48898. if (tempVector3.y < this._orthoBottom)
  48899. this._orthoBottom = tempVector3.y;
  48900. if (tempVector3.x > this._orthoRight)
  48901. this._orthoRight = tempVector3.x;
  48902. if (tempVector3.y > this._orthoTop)
  48903. this._orthoTop = tempVector3.y;
  48904. }
  48905. }
  48906. }
  48907. var xOffset = this._orthoRight - this._orthoLeft;
  48908. var yOffset = this._orthoTop - this._orthoBottom;
  48909. 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);
  48910. };
  48911. DirectionalLight.prototype._buildUniformLayout = function () {
  48912. this._uniformBuffer.addUniform("vLightData", 4);
  48913. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48914. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48915. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48916. this._uniformBuffer.addUniform("depthValues", 2);
  48917. this._uniformBuffer.create();
  48918. };
  48919. /**
  48920. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48921. * @param effect The effect to update
  48922. * @param lightIndex The index of the light in the effect to update
  48923. * @returns The directional light
  48924. */
  48925. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48926. if (this.computeTransformedInformation()) {
  48927. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48928. return this;
  48929. }
  48930. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48931. return this;
  48932. };
  48933. /**
  48934. * Gets the minZ used for shadow according to both the scene and the light.
  48935. *
  48936. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48937. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48938. * @param activeCamera The camera we are returning the min for
  48939. * @returns the depth min z
  48940. */
  48941. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48942. return 1;
  48943. };
  48944. /**
  48945. * Gets the maxZ used for shadow according to both the scene and the light.
  48946. *
  48947. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48948. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48949. * @param activeCamera The camera we are returning the max for
  48950. * @returns the depth max z
  48951. */
  48952. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48953. return 1;
  48954. };
  48955. __decorate([
  48956. BABYLON.serialize()
  48957. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48958. __decorate([
  48959. BABYLON.serialize()
  48960. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48961. __decorate([
  48962. BABYLON.serialize()
  48963. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48964. return DirectionalLight;
  48965. }(BABYLON.ShadowLight));
  48966. BABYLON.DirectionalLight = DirectionalLight;
  48967. })(BABYLON || (BABYLON = {}));
  48968. //# sourceMappingURL=babylon.directionalLight.js.map
  48969. "use strict";
  48970. var BABYLON;
  48971. (function (BABYLON) {
  48972. /**
  48973. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48974. * These values define a cone of light starting from the position, emitting toward the direction.
  48975. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48976. * and the exponent defines the speed of the decay of the light with distance (reach).
  48977. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48978. */
  48979. var SpotLight = /** @class */ (function (_super) {
  48980. __extends(SpotLight, _super);
  48981. /**
  48982. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48983. * It can cast shadows.
  48984. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48985. * @param name The light friendly name
  48986. * @param position The position of the spot light in the scene
  48987. * @param direction The direction of the light in the scene
  48988. * @param angle The cone angle of the light in Radians
  48989. * @param exponent The light decay speed with the distance from the emission spot
  48990. * @param scene The scene the lights belongs to
  48991. */
  48992. function SpotLight(name, position, direction, angle, exponent, scene) {
  48993. var _this = _super.call(this, name, scene) || this;
  48994. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48995. _this._projectionTextureLightNear = 1e-6;
  48996. _this._projectionTextureLightFar = 1000.0;
  48997. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48998. _this._projectionTextureViewLightDirty = true;
  48999. _this._projectionTextureProjectionLightDirty = true;
  49000. _this._projectionTextureDirty = true;
  49001. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49002. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49003. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49004. _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);
  49005. _this.position = position;
  49006. _this.direction = direction;
  49007. _this.angle = angle;
  49008. _this.exponent = exponent;
  49009. return _this;
  49010. }
  49011. Object.defineProperty(SpotLight.prototype, "angle", {
  49012. /**
  49013. * Gets the cone angle of the spot light in Radians.
  49014. */
  49015. get: function () {
  49016. return this._angle;
  49017. },
  49018. /**
  49019. * Sets the cone angle of the spot light in Radians.
  49020. */
  49021. set: function (value) {
  49022. this._angle = value;
  49023. this._projectionTextureProjectionLightDirty = true;
  49024. this.forceProjectionMatrixCompute();
  49025. },
  49026. enumerable: true,
  49027. configurable: true
  49028. });
  49029. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49030. /**
  49031. * Allows scaling the angle of the light for shadow generation only.
  49032. */
  49033. get: function () {
  49034. return this._shadowAngleScale;
  49035. },
  49036. /**
  49037. * Allows scaling the angle of the light for shadow generation only.
  49038. */
  49039. set: function (value) {
  49040. this._shadowAngleScale = value;
  49041. this.forceProjectionMatrixCompute();
  49042. },
  49043. enumerable: true,
  49044. configurable: true
  49045. });
  49046. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49047. /**
  49048. * Allows reading the projecton texture
  49049. */
  49050. get: function () {
  49051. return this._projectionTextureMatrix;
  49052. },
  49053. enumerable: true,
  49054. configurable: true
  49055. });
  49056. ;
  49057. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49058. /**
  49059. * Gets the near clip of the Spotlight for texture projection.
  49060. */
  49061. get: function () {
  49062. return this._projectionTextureLightNear;
  49063. },
  49064. /**
  49065. * Sets the near clip of the Spotlight for texture projection.
  49066. */
  49067. set: function (value) {
  49068. this._projectionTextureLightNear = value;
  49069. this._projectionTextureProjectionLightDirty = true;
  49070. },
  49071. enumerable: true,
  49072. configurable: true
  49073. });
  49074. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49075. /**
  49076. * Gets the far clip of the Spotlight for texture projection.
  49077. */
  49078. get: function () {
  49079. return this._projectionTextureLightFar;
  49080. },
  49081. /**
  49082. * Sets the far clip of the Spotlight for texture projection.
  49083. */
  49084. set: function (value) {
  49085. this._projectionTextureLightFar = value;
  49086. this._projectionTextureProjectionLightDirty = true;
  49087. },
  49088. enumerable: true,
  49089. configurable: true
  49090. });
  49091. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49092. /**
  49093. * Gets the Up vector of the Spotlight for texture projection.
  49094. */
  49095. get: function () {
  49096. return this._projectionTextureUpDirection;
  49097. },
  49098. /**
  49099. * Sets the Up vector of the Spotlight for texture projection.
  49100. */
  49101. set: function (value) {
  49102. this._projectionTextureUpDirection = value;
  49103. this._projectionTextureProjectionLightDirty = true;
  49104. },
  49105. enumerable: true,
  49106. configurable: true
  49107. });
  49108. ;
  49109. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49110. /**
  49111. * Gets the projection texture of the light.
  49112. */
  49113. get: function () {
  49114. return this._projectionTexture;
  49115. },
  49116. /**
  49117. * Sets the projection texture of the light.
  49118. */
  49119. set: function (value) {
  49120. this._projectionTexture = value;
  49121. this._projectionTextureDirty = true;
  49122. },
  49123. enumerable: true,
  49124. configurable: true
  49125. });
  49126. /**
  49127. * Returns the string "SpotLight".
  49128. * @returns the class name
  49129. */
  49130. SpotLight.prototype.getClassName = function () {
  49131. return "SpotLight";
  49132. };
  49133. /**
  49134. * Returns the integer 2.
  49135. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49136. */
  49137. SpotLight.prototype.getTypeID = function () {
  49138. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49139. };
  49140. /**
  49141. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49142. */
  49143. SpotLight.prototype._setDirection = function (value) {
  49144. _super.prototype._setDirection.call(this, value);
  49145. this._projectionTextureViewLightDirty = true;
  49146. };
  49147. /**
  49148. * Overrides the position setter to recompute the projection texture view light Matrix.
  49149. */
  49150. SpotLight.prototype._setPosition = function (value) {
  49151. _super.prototype._setPosition.call(this, value);
  49152. this._projectionTextureViewLightDirty = true;
  49153. };
  49154. /**
  49155. * 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.
  49156. * Returns the SpotLight.
  49157. */
  49158. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49159. var activeCamera = this.getScene().activeCamera;
  49160. if (!activeCamera) {
  49161. return;
  49162. }
  49163. this._shadowAngleScale = this._shadowAngleScale || 1;
  49164. var angle = this._shadowAngleScale * this._angle;
  49165. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49166. };
  49167. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49168. this._projectionTextureViewLightDirty = false;
  49169. this._projectionTextureDirty = true;
  49170. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49171. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49172. };
  49173. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49174. this._projectionTextureProjectionLightDirty = false;
  49175. this._projectionTextureDirty = true;
  49176. var light_far = this.projectionTextureLightFar;
  49177. var light_near = this.projectionTextureLightNear;
  49178. var P = light_far / (light_far - light_near);
  49179. var Q = -P * light_near;
  49180. var S = 1.0 / Math.tan(this._angle / 2.0);
  49181. var A = 1.0;
  49182. 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);
  49183. };
  49184. /**
  49185. * Main function for light texture projection matrix computing.
  49186. */
  49187. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49188. this._projectionTextureDirty = false;
  49189. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49190. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49191. };
  49192. SpotLight.prototype._buildUniformLayout = function () {
  49193. this._uniformBuffer.addUniform("vLightData", 4);
  49194. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49195. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49196. this._uniformBuffer.addUniform("vLightDirection", 3);
  49197. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49198. this._uniformBuffer.addUniform("depthValues", 2);
  49199. this._uniformBuffer.create();
  49200. };
  49201. /**
  49202. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49203. * @param effect The effect to update
  49204. * @param lightIndex The index of the light in the effect to update
  49205. * @returns The spot light
  49206. */
  49207. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49208. var normalizeDirection;
  49209. if (this.computeTransformedInformation()) {
  49210. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49211. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49212. }
  49213. else {
  49214. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49215. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49216. }
  49217. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49218. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49219. if (this._projectionTextureViewLightDirty) {
  49220. this._computeProjectionTextureViewLightMatrix();
  49221. }
  49222. if (this._projectionTextureProjectionLightDirty) {
  49223. this._computeProjectionTextureProjectionLightMatrix();
  49224. }
  49225. if (this._projectionTextureDirty) {
  49226. this._computeProjectionTextureMatrix();
  49227. }
  49228. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49229. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49230. }
  49231. return this;
  49232. };
  49233. /**
  49234. * Disposes the light and the associated resources.
  49235. */
  49236. SpotLight.prototype.dispose = function () {
  49237. _super.prototype.dispose.call(this);
  49238. if (this._projectionTexture) {
  49239. this._projectionTexture.dispose();
  49240. }
  49241. };
  49242. __decorate([
  49243. BABYLON.serialize()
  49244. ], SpotLight.prototype, "angle", null);
  49245. __decorate([
  49246. BABYLON.serialize()
  49247. ], SpotLight.prototype, "shadowAngleScale", null);
  49248. __decorate([
  49249. BABYLON.serialize()
  49250. ], SpotLight.prototype, "exponent", void 0);
  49251. __decorate([
  49252. BABYLON.serialize()
  49253. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49254. __decorate([
  49255. BABYLON.serialize()
  49256. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49257. __decorate([
  49258. BABYLON.serialize()
  49259. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49260. __decorate([
  49261. BABYLON.serializeAsTexture("projectedLightTexture")
  49262. ], SpotLight.prototype, "_projectionTexture", void 0);
  49263. return SpotLight;
  49264. }(BABYLON.ShadowLight));
  49265. BABYLON.SpotLight = SpotLight;
  49266. })(BABYLON || (BABYLON = {}));
  49267. //# sourceMappingURL=babylon.spotLight.js.map
  49268. "use strict";
  49269. var BABYLON;
  49270. (function (BABYLON) {
  49271. /**
  49272. * Class used to override all child animations of a given target
  49273. */
  49274. var AnimationPropertiesOverride = /** @class */ (function () {
  49275. function AnimationPropertiesOverride() {
  49276. /**
  49277. * Gets or sets a value indicating if animation blending must be used
  49278. */
  49279. this.enableBlending = false;
  49280. /**
  49281. * Gets or sets the blending speed to use when enableBlending is true
  49282. */
  49283. this.blendingSpeed = 0.01;
  49284. /**
  49285. * Gets or sets the default loop mode to use
  49286. */
  49287. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49288. }
  49289. return AnimationPropertiesOverride;
  49290. }());
  49291. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49292. })(BABYLON || (BABYLON = {}));
  49293. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49294. "use strict";
  49295. var BABYLON;
  49296. (function (BABYLON) {
  49297. var AnimationRange = /** @class */ (function () {
  49298. function AnimationRange(name, from, to) {
  49299. this.name = name;
  49300. this.from = from;
  49301. this.to = to;
  49302. }
  49303. AnimationRange.prototype.clone = function () {
  49304. return new AnimationRange(this.name, this.from, this.to);
  49305. };
  49306. return AnimationRange;
  49307. }());
  49308. BABYLON.AnimationRange = AnimationRange;
  49309. /**
  49310. * Composed of a frame, and an action function
  49311. */
  49312. var AnimationEvent = /** @class */ (function () {
  49313. function AnimationEvent(frame, action, onlyOnce) {
  49314. this.frame = frame;
  49315. this.action = action;
  49316. this.onlyOnce = onlyOnce;
  49317. this.isDone = false;
  49318. }
  49319. return AnimationEvent;
  49320. }());
  49321. BABYLON.AnimationEvent = AnimationEvent;
  49322. var PathCursor = /** @class */ (function () {
  49323. function PathCursor(path) {
  49324. this.path = path;
  49325. this._onchange = new Array();
  49326. this.value = 0;
  49327. this.animations = new Array();
  49328. }
  49329. PathCursor.prototype.getPoint = function () {
  49330. var point = this.path.getPointAtLengthPosition(this.value);
  49331. return new BABYLON.Vector3(point.x, 0, point.y);
  49332. };
  49333. PathCursor.prototype.moveAhead = function (step) {
  49334. if (step === void 0) { step = 0.002; }
  49335. this.move(step);
  49336. return this;
  49337. };
  49338. PathCursor.prototype.moveBack = function (step) {
  49339. if (step === void 0) { step = 0.002; }
  49340. this.move(-step);
  49341. return this;
  49342. };
  49343. PathCursor.prototype.move = function (step) {
  49344. if (Math.abs(step) > 1) {
  49345. throw "step size should be less than 1.";
  49346. }
  49347. this.value += step;
  49348. this.ensureLimits();
  49349. this.raiseOnChange();
  49350. return this;
  49351. };
  49352. PathCursor.prototype.ensureLimits = function () {
  49353. while (this.value > 1) {
  49354. this.value -= 1;
  49355. }
  49356. while (this.value < 0) {
  49357. this.value += 1;
  49358. }
  49359. return this;
  49360. };
  49361. // used by animation engine
  49362. PathCursor.prototype.raiseOnChange = function () {
  49363. var _this = this;
  49364. this._onchange.forEach(function (f) { return f(_this); });
  49365. return this;
  49366. };
  49367. PathCursor.prototype.onchange = function (f) {
  49368. this._onchange.push(f);
  49369. return this;
  49370. };
  49371. return PathCursor;
  49372. }());
  49373. BABYLON.PathCursor = PathCursor;
  49374. var AnimationKeyInterpolation;
  49375. (function (AnimationKeyInterpolation) {
  49376. /**
  49377. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  49378. */
  49379. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49380. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49381. var Animation = /** @class */ (function () {
  49382. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  49383. this.name = name;
  49384. this.targetProperty = targetProperty;
  49385. this.framePerSecond = framePerSecond;
  49386. this.dataType = dataType;
  49387. this.loopMode = loopMode;
  49388. this.enableBlending = enableBlending;
  49389. this._runtimeAnimations = new Array();
  49390. // The set of event that will be linked to this animation
  49391. this._events = new Array();
  49392. this.blendingSpeed = 0.01;
  49393. this._ranges = {};
  49394. this.targetPropertyPath = targetProperty.split(".");
  49395. this.dataType = dataType;
  49396. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49397. }
  49398. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49399. var dataType = undefined;
  49400. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49401. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49402. }
  49403. else if (from instanceof BABYLON.Quaternion) {
  49404. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49405. }
  49406. else if (from instanceof BABYLON.Vector3) {
  49407. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49408. }
  49409. else if (from instanceof BABYLON.Vector2) {
  49410. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49411. }
  49412. else if (from instanceof BABYLON.Color3) {
  49413. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49414. }
  49415. else if (from instanceof BABYLON.Size) {
  49416. dataType = Animation.ANIMATIONTYPE_SIZE;
  49417. }
  49418. if (dataType == undefined) {
  49419. return null;
  49420. }
  49421. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49422. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49423. animation.setKeys(keys);
  49424. if (easingFunction !== undefined) {
  49425. animation.setEasingFunction(easingFunction);
  49426. }
  49427. return animation;
  49428. };
  49429. /**
  49430. * Sets up an animation.
  49431. * @param property the property to animate
  49432. * @param animationType the animation type to apply
  49433. * @param easingFunction the easing function used in the animation
  49434. * @returns The created animation
  49435. */
  49436. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49437. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49438. animation.setEasingFunction(easingFunction);
  49439. return animation;
  49440. };
  49441. /**
  49442. * Create and start an animation on a node
  49443. * @param {string} name defines the name of the global animation that will be run on all nodes
  49444. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49445. * @param {string} targetProperty defines property to animate
  49446. * @param {number} framePerSecond defines the number of frame per second yo use
  49447. * @param {number} totalFrame defines the number of frames in total
  49448. * @param {any} from defines the initial value
  49449. * @param {any} to defines the final value
  49450. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49451. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49452. * @param onAnimationEnd defines the callback to call when animation end
  49453. * @returns the animatable created for this animation
  49454. */
  49455. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49456. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49457. if (!animation) {
  49458. return null;
  49459. }
  49460. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49461. };
  49462. /**
  49463. * Create and start an animation on a node and its descendants
  49464. * @param {string} name defines the name of the global animation that will be run on all nodes
  49465. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49466. * @param {boolean} 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.
  49467. * @param {string} targetProperty defines property to animate
  49468. * @param {number} framePerSecond defines the number of frame per second yo use
  49469. * @param {number} totalFrame defines the number of frames in total
  49470. * @param {any} from defines the initial value
  49471. * @param {any} to defines the final value
  49472. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49473. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49474. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49475. * @returns the list of animatables created for all nodes
  49476. * @example https://www.babylonjs-playground.com/#MH0VLI
  49477. */
  49478. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49479. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49480. if (!animation) {
  49481. return null;
  49482. }
  49483. var scene = node.getScene();
  49484. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49485. };
  49486. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49487. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49488. if (!animation) {
  49489. return null;
  49490. }
  49491. node.animations.push(animation);
  49492. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49493. };
  49494. /**
  49495. * Transition property of the Camera to the target Value.
  49496. * @param property The property to transition
  49497. * @param targetValue The target Value of the property
  49498. * @param host The object where the property to animate belongs
  49499. * @param scene Scene used to run the animation
  49500. * @param frameRate Framerate (in frame/s) to use
  49501. * @param transition The transition type we want to use
  49502. * @param duration The duration of the animation, in milliseconds
  49503. * @param onAnimationEnd Call back trigger at the end of the animation.
  49504. */
  49505. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49506. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49507. if (duration <= 0) {
  49508. host[property] = targetValue;
  49509. if (onAnimationEnd) {
  49510. onAnimationEnd();
  49511. }
  49512. return null;
  49513. }
  49514. var endFrame = frameRate * (duration / 1000);
  49515. transition.setKeys([{
  49516. frame: 0,
  49517. value: host[property].clone ? host[property].clone() : host[property]
  49518. },
  49519. {
  49520. frame: endFrame,
  49521. value: targetValue
  49522. }]);
  49523. if (!host.animations) {
  49524. host.animations = [];
  49525. }
  49526. host.animations.push(transition);
  49527. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49528. animation.onAnimationEnd = onAnimationEnd;
  49529. return animation;
  49530. };
  49531. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49532. /**
  49533. * Return the array of runtime animations currently using this animation
  49534. */
  49535. get: function () {
  49536. return this._runtimeAnimations;
  49537. },
  49538. enumerable: true,
  49539. configurable: true
  49540. });
  49541. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49542. get: function () {
  49543. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49544. var runtimeAnimation = _a[_i];
  49545. if (!runtimeAnimation.isStopped) {
  49546. return true;
  49547. }
  49548. }
  49549. return false;
  49550. },
  49551. enumerable: true,
  49552. configurable: true
  49553. });
  49554. // Methods
  49555. /**
  49556. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  49557. */
  49558. Animation.prototype.toString = function (fullDetails) {
  49559. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49560. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49561. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49562. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49563. if (fullDetails) {
  49564. ret += ", Ranges: {";
  49565. var first = true;
  49566. for (var name in this._ranges) {
  49567. if (first) {
  49568. ret += ", ";
  49569. first = false;
  49570. }
  49571. ret += name;
  49572. }
  49573. ret += "}";
  49574. }
  49575. return ret;
  49576. };
  49577. /**
  49578. * Add an event to this animation.
  49579. */
  49580. Animation.prototype.addEvent = function (event) {
  49581. this._events.push(event);
  49582. };
  49583. /**
  49584. * Remove all events found at the given frame
  49585. * @param frame
  49586. */
  49587. Animation.prototype.removeEvents = function (frame) {
  49588. for (var index = 0; index < this._events.length; index++) {
  49589. if (this._events[index].frame === frame) {
  49590. this._events.splice(index, 1);
  49591. index--;
  49592. }
  49593. }
  49594. };
  49595. Animation.prototype.getEvents = function () {
  49596. return this._events;
  49597. };
  49598. Animation.prototype.createRange = function (name, from, to) {
  49599. // check name not already in use; could happen for bones after serialized
  49600. if (!this._ranges[name]) {
  49601. this._ranges[name] = new AnimationRange(name, from, to);
  49602. }
  49603. };
  49604. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49605. if (deleteFrames === void 0) { deleteFrames = true; }
  49606. var range = this._ranges[name];
  49607. if (!range) {
  49608. return;
  49609. }
  49610. if (deleteFrames) {
  49611. var from = range.from;
  49612. var to = range.to;
  49613. // this loop MUST go high to low for multiple splices to work
  49614. for (var key = this._keys.length - 1; key >= 0; key--) {
  49615. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49616. this._keys.splice(key, 1);
  49617. }
  49618. }
  49619. }
  49620. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49621. };
  49622. Animation.prototype.getRange = function (name) {
  49623. return this._ranges[name];
  49624. };
  49625. Animation.prototype.getKeys = function () {
  49626. return this._keys;
  49627. };
  49628. Animation.prototype.getHighestFrame = function () {
  49629. var ret = 0;
  49630. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49631. if (ret < this._keys[key].frame) {
  49632. ret = this._keys[key].frame;
  49633. }
  49634. }
  49635. return ret;
  49636. };
  49637. Animation.prototype.getEasingFunction = function () {
  49638. return this._easingFunction;
  49639. };
  49640. Animation.prototype.setEasingFunction = function (easingFunction) {
  49641. this._easingFunction = easingFunction;
  49642. };
  49643. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49644. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49645. };
  49646. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49647. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49648. };
  49649. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49650. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49651. };
  49652. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49653. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49654. };
  49655. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49656. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49657. };
  49658. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49659. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49660. };
  49661. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49662. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49663. };
  49664. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49665. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49666. };
  49667. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49668. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49669. };
  49670. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49671. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49672. };
  49673. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  49674. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49675. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49676. }
  49677. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49678. };
  49679. Animation.prototype.clone = function () {
  49680. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49681. clone.enableBlending = this.enableBlending;
  49682. clone.blendingSpeed = this.blendingSpeed;
  49683. if (this._keys) {
  49684. clone.setKeys(this._keys);
  49685. }
  49686. if (this._ranges) {
  49687. clone._ranges = {};
  49688. for (var name in this._ranges) {
  49689. var range = this._ranges[name];
  49690. if (!range) {
  49691. continue;
  49692. }
  49693. clone._ranges[name] = range.clone();
  49694. }
  49695. }
  49696. return clone;
  49697. };
  49698. Animation.prototype.setKeys = function (values) {
  49699. this._keys = values.slice(0);
  49700. };
  49701. Animation.prototype.serialize = function () {
  49702. var serializationObject = {};
  49703. serializationObject.name = this.name;
  49704. serializationObject.property = this.targetProperty;
  49705. serializationObject.framePerSecond = this.framePerSecond;
  49706. serializationObject.dataType = this.dataType;
  49707. serializationObject.loopBehavior = this.loopMode;
  49708. serializationObject.enableBlending = this.enableBlending;
  49709. serializationObject.blendingSpeed = this.blendingSpeed;
  49710. var dataType = this.dataType;
  49711. serializationObject.keys = [];
  49712. var keys = this.getKeys();
  49713. for (var index = 0; index < keys.length; index++) {
  49714. var animationKey = keys[index];
  49715. var key = {};
  49716. key.frame = animationKey.frame;
  49717. switch (dataType) {
  49718. case Animation.ANIMATIONTYPE_FLOAT:
  49719. key.values = [animationKey.value];
  49720. break;
  49721. case Animation.ANIMATIONTYPE_QUATERNION:
  49722. case Animation.ANIMATIONTYPE_MATRIX:
  49723. case Animation.ANIMATIONTYPE_VECTOR3:
  49724. case Animation.ANIMATIONTYPE_COLOR3:
  49725. key.values = animationKey.value.asArray();
  49726. break;
  49727. }
  49728. serializationObject.keys.push(key);
  49729. }
  49730. serializationObject.ranges = [];
  49731. for (var name in this._ranges) {
  49732. var source = this._ranges[name];
  49733. if (!source) {
  49734. continue;
  49735. }
  49736. var range = {};
  49737. range.name = name;
  49738. range.from = source.from;
  49739. range.to = source.to;
  49740. serializationObject.ranges.push(range);
  49741. }
  49742. return serializationObject;
  49743. };
  49744. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49745. get: function () {
  49746. return Animation._ANIMATIONTYPE_FLOAT;
  49747. },
  49748. enumerable: true,
  49749. configurable: true
  49750. });
  49751. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49752. get: function () {
  49753. return Animation._ANIMATIONTYPE_VECTOR3;
  49754. },
  49755. enumerable: true,
  49756. configurable: true
  49757. });
  49758. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49759. get: function () {
  49760. return Animation._ANIMATIONTYPE_VECTOR2;
  49761. },
  49762. enumerable: true,
  49763. configurable: true
  49764. });
  49765. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  49766. get: function () {
  49767. return Animation._ANIMATIONTYPE_SIZE;
  49768. },
  49769. enumerable: true,
  49770. configurable: true
  49771. });
  49772. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  49773. get: function () {
  49774. return Animation._ANIMATIONTYPE_QUATERNION;
  49775. },
  49776. enumerable: true,
  49777. configurable: true
  49778. });
  49779. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  49780. get: function () {
  49781. return Animation._ANIMATIONTYPE_MATRIX;
  49782. },
  49783. enumerable: true,
  49784. configurable: true
  49785. });
  49786. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  49787. get: function () {
  49788. return Animation._ANIMATIONTYPE_COLOR3;
  49789. },
  49790. enumerable: true,
  49791. configurable: true
  49792. });
  49793. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  49794. get: function () {
  49795. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  49796. },
  49797. enumerable: true,
  49798. configurable: true
  49799. });
  49800. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  49801. get: function () {
  49802. return Animation._ANIMATIONLOOPMODE_CYCLE;
  49803. },
  49804. enumerable: true,
  49805. configurable: true
  49806. });
  49807. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  49808. get: function () {
  49809. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  49810. },
  49811. enumerable: true,
  49812. configurable: true
  49813. });
  49814. Animation.Parse = function (parsedAnimation) {
  49815. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  49816. var dataType = parsedAnimation.dataType;
  49817. var keys = [];
  49818. var data;
  49819. var index;
  49820. if (parsedAnimation.enableBlending) {
  49821. animation.enableBlending = parsedAnimation.enableBlending;
  49822. }
  49823. if (parsedAnimation.blendingSpeed) {
  49824. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  49825. }
  49826. for (index = 0; index < parsedAnimation.keys.length; index++) {
  49827. var key = parsedAnimation.keys[index];
  49828. var inTangent;
  49829. var outTangent;
  49830. switch (dataType) {
  49831. case Animation.ANIMATIONTYPE_FLOAT:
  49832. data = key.values[0];
  49833. if (key.values.length >= 1) {
  49834. inTangent = key.values[1];
  49835. }
  49836. if (key.values.length >= 2) {
  49837. outTangent = key.values[2];
  49838. }
  49839. break;
  49840. case Animation.ANIMATIONTYPE_QUATERNION:
  49841. data = BABYLON.Quaternion.FromArray(key.values);
  49842. if (key.values.length >= 8) {
  49843. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  49844. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  49845. inTangent = _inTangent;
  49846. }
  49847. }
  49848. if (key.values.length >= 12) {
  49849. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  49850. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  49851. outTangent = _outTangent;
  49852. }
  49853. }
  49854. break;
  49855. case Animation.ANIMATIONTYPE_MATRIX:
  49856. data = BABYLON.Matrix.FromArray(key.values);
  49857. break;
  49858. case Animation.ANIMATIONTYPE_COLOR3:
  49859. data = BABYLON.Color3.FromArray(key.values);
  49860. break;
  49861. case Animation.ANIMATIONTYPE_VECTOR3:
  49862. default:
  49863. data = BABYLON.Vector3.FromArray(key.values);
  49864. break;
  49865. }
  49866. var keyData = {};
  49867. keyData.frame = key.frame;
  49868. keyData.value = data;
  49869. if (inTangent != undefined) {
  49870. keyData.inTangent = inTangent;
  49871. }
  49872. if (outTangent != undefined) {
  49873. keyData.outTangent = outTangent;
  49874. }
  49875. keys.push(keyData);
  49876. }
  49877. animation.setKeys(keys);
  49878. if (parsedAnimation.ranges) {
  49879. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  49880. data = parsedAnimation.ranges[index];
  49881. animation.createRange(data.name, data.from, data.to);
  49882. }
  49883. }
  49884. return animation;
  49885. };
  49886. Animation.AppendSerializedAnimations = function (source, destination) {
  49887. if (source.animations) {
  49888. destination.animations = [];
  49889. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  49890. var animation = source.animations[animationIndex];
  49891. destination.animations.push(animation.serialize());
  49892. }
  49893. }
  49894. };
  49895. /**
  49896. * Use matrix interpolation instead of using direct key value when animating matrices
  49897. */
  49898. Animation.AllowMatricesInterpolation = false;
  49899. /**
  49900. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  49901. */
  49902. Animation.AllowMatrixDecomposeForInterpolation = true;
  49903. // Statics
  49904. Animation._ANIMATIONTYPE_FLOAT = 0;
  49905. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  49906. Animation._ANIMATIONTYPE_QUATERNION = 2;
  49907. Animation._ANIMATIONTYPE_MATRIX = 3;
  49908. Animation._ANIMATIONTYPE_COLOR3 = 4;
  49909. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  49910. Animation._ANIMATIONTYPE_SIZE = 6;
  49911. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  49912. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  49913. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  49914. return Animation;
  49915. }());
  49916. BABYLON.Animation = Animation;
  49917. })(BABYLON || (BABYLON = {}));
  49918. //# sourceMappingURL=babylon.animation.js.map
  49919. "use strict";
  49920. var BABYLON;
  49921. (function (BABYLON) {
  49922. /**
  49923. * This class defines the direct association between an animation and a target
  49924. */
  49925. var TargetedAnimation = /** @class */ (function () {
  49926. function TargetedAnimation() {
  49927. }
  49928. return TargetedAnimation;
  49929. }());
  49930. BABYLON.TargetedAnimation = TargetedAnimation;
  49931. /**
  49932. * Use this class to create coordinated animations on multiple targets
  49933. */
  49934. var AnimationGroup = /** @class */ (function () {
  49935. function AnimationGroup(name, scene) {
  49936. if (scene === void 0) { scene = null; }
  49937. this.name = name;
  49938. this._targetedAnimations = new Array();
  49939. this._animatables = new Array();
  49940. this._from = Number.MAX_VALUE;
  49941. this._to = -Number.MAX_VALUE;
  49942. this._speedRatio = 1;
  49943. this.onAnimationEndObservable = new BABYLON.Observable();
  49944. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49945. this._scene.animationGroups.push(this);
  49946. }
  49947. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  49948. /**
  49949. * Define if the animations are started
  49950. */
  49951. get: function () {
  49952. return this._isStarted;
  49953. },
  49954. enumerable: true,
  49955. configurable: true
  49956. });
  49957. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  49958. /**
  49959. * Gets or sets the speed ratio to use for all animations
  49960. */
  49961. get: function () {
  49962. return this._speedRatio;
  49963. },
  49964. /**
  49965. * Gets or sets the speed ratio to use for all animations
  49966. */
  49967. set: function (value) {
  49968. if (this._speedRatio === value) {
  49969. return;
  49970. }
  49971. this._speedRatio = value;
  49972. for (var index = 0; index < this._animatables.length; index++) {
  49973. var animatable = this._animatables[index];
  49974. animatable.speedRatio = this._speedRatio;
  49975. }
  49976. },
  49977. enumerable: true,
  49978. configurable: true
  49979. });
  49980. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  49981. /**
  49982. * Gets the targeted animations for this animation group
  49983. */
  49984. get: function () {
  49985. return this._targetedAnimations;
  49986. },
  49987. enumerable: true,
  49988. configurable: true
  49989. });
  49990. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  49991. /**
  49992. * returning the list of animatables controlled by this animation group.
  49993. */
  49994. get: function () {
  49995. return this._animatables;
  49996. },
  49997. enumerable: true,
  49998. configurable: true
  49999. });
  50000. /**
  50001. * Add an animation (with its target) in the group
  50002. * @param animation defines the animation we want to add
  50003. * @param target defines the target of the animation
  50004. * @returns the {BABYLON.TargetedAnimation} object
  50005. */
  50006. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50007. var targetedAnimation = {
  50008. animation: animation,
  50009. target: target
  50010. };
  50011. var keys = animation.getKeys();
  50012. if (this._from > keys[0].frame) {
  50013. this._from = keys[0].frame;
  50014. }
  50015. if (this._to < keys[keys.length - 1].frame) {
  50016. this._to = keys[keys.length - 1].frame;
  50017. }
  50018. this._targetedAnimations.push(targetedAnimation);
  50019. return targetedAnimation;
  50020. };
  50021. /**
  50022. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50023. * It can add constant keys at begin or end
  50024. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  50025. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  50026. */
  50027. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50028. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  50029. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  50030. beginFrame = Math.max(beginFrame, this._from);
  50031. endFrame = Math.min(endFrame, this._to);
  50032. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50033. var targetedAnimation = this._targetedAnimations[index];
  50034. var keys = targetedAnimation.animation.getKeys();
  50035. var startKey = keys[0];
  50036. var endKey = keys[keys.length - 1];
  50037. if (startKey.frame > beginFrame) {
  50038. var newKey = {
  50039. frame: beginFrame,
  50040. value: startKey.value,
  50041. inTangent: startKey.inTangent,
  50042. outTangent: startKey.outTangent,
  50043. interpolation: startKey.interpolation
  50044. };
  50045. keys.splice(0, 0, newKey);
  50046. }
  50047. if (endKey.frame < endFrame) {
  50048. var newKey = {
  50049. frame: endFrame,
  50050. value: endKey.value,
  50051. inTangent: endKey.outTangent,
  50052. outTangent: endKey.outTangent,
  50053. interpolation: endKey.interpolation
  50054. };
  50055. keys.push(newKey);
  50056. }
  50057. }
  50058. return this;
  50059. };
  50060. /**
  50061. * Start all animations on given targets
  50062. * @param loop defines if animations must loop
  50063. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50064. * @param from defines the from key (optional)
  50065. * @param to defines the to key (optional)
  50066. * @returns the current animation group
  50067. */
  50068. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50069. var _this = this;
  50070. if (loop === void 0) { loop = false; }
  50071. if (speedRatio === void 0) { speedRatio = 1; }
  50072. if (this._isStarted || this._targetedAnimations.length === 0) {
  50073. return this;
  50074. }
  50075. var _loop_1 = function () {
  50076. var targetedAnimation = this_1._targetedAnimations[index];
  50077. if (!targetedAnimation.target.animations) {
  50078. targetedAnimation.target.animations = [];
  50079. }
  50080. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  50081. targetedAnimation.target.animations.push(targetedAnimation.animation);
  50082. }
  50083. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  50084. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50085. }));
  50086. };
  50087. var this_1 = this;
  50088. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50089. _loop_1();
  50090. }
  50091. this._speedRatio = speedRatio;
  50092. this._isStarted = true;
  50093. return this;
  50094. };
  50095. /**
  50096. * Pause all animations
  50097. */
  50098. AnimationGroup.prototype.pause = function () {
  50099. if (!this._isStarted) {
  50100. return this;
  50101. }
  50102. for (var index = 0; index < this._animatables.length; index++) {
  50103. var animatable = this._animatables[index];
  50104. animatable.pause();
  50105. }
  50106. return this;
  50107. };
  50108. /**
  50109. * Play all animations to initial state
  50110. * This function will start() the animations if they were not started or will restart() them if they were paused
  50111. * @param loop defines if animations must loop
  50112. */
  50113. AnimationGroup.prototype.play = function (loop) {
  50114. if (this.isStarted) {
  50115. if (loop !== undefined) {
  50116. for (var index = 0; index < this._animatables.length; index++) {
  50117. var animatable = this._animatables[index];
  50118. animatable.loopAnimation = loop;
  50119. }
  50120. }
  50121. this.restart();
  50122. }
  50123. else {
  50124. this.start(loop, this._speedRatio);
  50125. }
  50126. return this;
  50127. };
  50128. /**
  50129. * Reset all animations to initial state
  50130. */
  50131. AnimationGroup.prototype.reset = function () {
  50132. if (!this._isStarted) {
  50133. return this;
  50134. }
  50135. for (var index = 0; index < this._animatables.length; index++) {
  50136. var animatable = this._animatables[index];
  50137. animatable.reset();
  50138. }
  50139. return this;
  50140. };
  50141. /**
  50142. * Restart animations from key 0
  50143. */
  50144. AnimationGroup.prototype.restart = function () {
  50145. if (!this._isStarted) {
  50146. return this;
  50147. }
  50148. for (var index = 0; index < this._animatables.length; index++) {
  50149. var animatable = this._animatables[index];
  50150. animatable.restart();
  50151. }
  50152. return this;
  50153. };
  50154. /**
  50155. * Stop all animations
  50156. */
  50157. AnimationGroup.prototype.stop = function () {
  50158. if (!this._isStarted) {
  50159. return this;
  50160. }
  50161. for (var index = 0; index < this._animatables.length; index++) {
  50162. var animatable = this._animatables[index];
  50163. animatable.stop();
  50164. }
  50165. this._isStarted = false;
  50166. return this;
  50167. };
  50168. /**
  50169. * Goes to a specific frame in this animation group
  50170. *
  50171. * @param frame the frame number to go to
  50172. * @return the animationGroup
  50173. */
  50174. AnimationGroup.prototype.goToFrame = function (frame) {
  50175. if (!this._isStarted) {
  50176. return this;
  50177. }
  50178. for (var index = 0; index < this._animatables.length; index++) {
  50179. var animatable = this._animatables[index];
  50180. animatable.goToFrame(frame);
  50181. }
  50182. return this;
  50183. };
  50184. /**
  50185. * Dispose all associated resources
  50186. */
  50187. AnimationGroup.prototype.dispose = function () {
  50188. this._targetedAnimations = [];
  50189. this._animatables = [];
  50190. var index = this._scene.animationGroups.indexOf(this);
  50191. if (index > -1) {
  50192. this._scene.animationGroups.splice(index, 1);
  50193. }
  50194. };
  50195. return AnimationGroup;
  50196. }());
  50197. BABYLON.AnimationGroup = AnimationGroup;
  50198. })(BABYLON || (BABYLON = {}));
  50199. //# sourceMappingURL=babylon.animationGroup.js.map
  50200. "use strict";
  50201. var BABYLON;
  50202. (function (BABYLON) {
  50203. var RuntimeAnimation = /** @class */ (function () {
  50204. /**
  50205. * Create a new RuntimeAnimation object
  50206. * @param target defines the target of the animation
  50207. * @param animation defines the source {BABYLON.Animation} object
  50208. * @param scene defines the hosting scene
  50209. * @param host defines the initiating Animatable
  50210. */
  50211. function RuntimeAnimation(target, animation, scene, host) {
  50212. this._currentFrame = 0;
  50213. this._offsetsCache = {};
  50214. this._highLimitsCache = {};
  50215. this._stopped = false;
  50216. this._blendingFactor = 0;
  50217. this._targetPath = "";
  50218. this._weight = 1.0;
  50219. this._ratioOffset = 0;
  50220. this._previousDelay = 0;
  50221. this._previousRatio = 0;
  50222. this._animation = animation;
  50223. this._target = target;
  50224. this._scene = scene;
  50225. this._host = host;
  50226. animation._runtimeAnimations.push(this);
  50227. }
  50228. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50229. /**
  50230. * Gets the current frame
  50231. */
  50232. get: function () {
  50233. return this._currentFrame;
  50234. },
  50235. enumerable: true,
  50236. configurable: true
  50237. });
  50238. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50239. /**
  50240. * Gets the weight of the runtime animation
  50241. */
  50242. get: function () {
  50243. return this._weight;
  50244. },
  50245. enumerable: true,
  50246. configurable: true
  50247. });
  50248. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  50249. /**
  50250. * Gets the original value of the runtime animation
  50251. */
  50252. get: function () {
  50253. return this._originalValue;
  50254. },
  50255. enumerable: true,
  50256. configurable: true
  50257. });
  50258. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50259. /**
  50260. * Gets the current value of the runtime animation
  50261. */
  50262. get: function () {
  50263. return this._currentValue;
  50264. },
  50265. enumerable: true,
  50266. configurable: true
  50267. });
  50268. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50269. /**
  50270. * Gets the path where to store the animated value in the target
  50271. */
  50272. get: function () {
  50273. return this._targetPath;
  50274. },
  50275. enumerable: true,
  50276. configurable: true
  50277. });
  50278. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50279. /**
  50280. * Gets the actual target of the runtime animation
  50281. */
  50282. get: function () {
  50283. return this._activeTarget;
  50284. },
  50285. enumerable: true,
  50286. configurable: true
  50287. });
  50288. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50289. get: function () {
  50290. return this._animation;
  50291. },
  50292. enumerable: true,
  50293. configurable: true
  50294. });
  50295. RuntimeAnimation.prototype.reset = function () {
  50296. this._offsetsCache = {};
  50297. this._highLimitsCache = {};
  50298. this._currentFrame = 0;
  50299. this._blendingFactor = 0;
  50300. this._originalValue = null;
  50301. };
  50302. RuntimeAnimation.prototype.isStopped = function () {
  50303. return this._stopped;
  50304. };
  50305. RuntimeAnimation.prototype.dispose = function () {
  50306. var index = this._animation.runtimeAnimations.indexOf(this);
  50307. if (index > -1) {
  50308. this._animation.runtimeAnimations.splice(index, 1);
  50309. }
  50310. };
  50311. RuntimeAnimation.prototype._getKeyValue = function (value) {
  50312. if (typeof value === "function") {
  50313. return value();
  50314. }
  50315. return value;
  50316. };
  50317. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50318. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50319. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50320. }
  50321. this._currentFrame = currentFrame;
  50322. var keys = this._animation.getKeys();
  50323. // Try to get a hash to find the right key
  50324. 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));
  50325. if (keys[startKeyIndex].frame >= currentFrame) {
  50326. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50327. startKeyIndex--;
  50328. }
  50329. }
  50330. for (var key = startKeyIndex; key < keys.length; key++) {
  50331. var endKey = keys[key + 1];
  50332. if (endKey.frame >= currentFrame) {
  50333. var startKey = keys[key];
  50334. var startValue = this._getKeyValue(startKey.value);
  50335. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  50336. return startValue;
  50337. }
  50338. var endValue = this._getKeyValue(endKey.value);
  50339. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50340. var frameDelta = endKey.frame - startKey.frame;
  50341. // gradient : percent of currentFrame between the frame inf and the frame sup
  50342. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50343. // check for easingFunction and correction of gradient
  50344. var easingFunction = this._animation.getEasingFunction();
  50345. if (easingFunction != null) {
  50346. gradient = easingFunction.ease(gradient);
  50347. }
  50348. switch (this._animation.dataType) {
  50349. // Float
  50350. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50351. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  50352. switch (loopMode) {
  50353. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50354. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50355. return floatValue;
  50356. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50357. return offsetValue * repeatCount + floatValue;
  50358. }
  50359. break;
  50360. // Quaternion
  50361. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50362. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  50363. switch (loopMode) {
  50364. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50365. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50366. return quatValue;
  50367. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50368. return quatValue.add(offsetValue.scale(repeatCount));
  50369. }
  50370. return quatValue;
  50371. // Vector3
  50372. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50373. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  50374. switch (loopMode) {
  50375. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50376. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50377. return vec3Value;
  50378. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50379. return vec3Value.add(offsetValue.scale(repeatCount));
  50380. }
  50381. // Vector2
  50382. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50383. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  50384. switch (loopMode) {
  50385. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50386. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50387. return vec2Value;
  50388. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50389. return vec2Value.add(offsetValue.scale(repeatCount));
  50390. }
  50391. // Size
  50392. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50393. switch (loopMode) {
  50394. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50395. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50396. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  50397. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50398. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50399. }
  50400. // Color3
  50401. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50402. switch (loopMode) {
  50403. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50404. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50405. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  50406. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50407. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50408. }
  50409. // Matrix
  50410. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  50411. switch (loopMode) {
  50412. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50413. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50414. if (BABYLON.Animation.AllowMatricesInterpolation) {
  50415. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  50416. }
  50417. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50418. return startValue;
  50419. }
  50420. default:
  50421. break;
  50422. }
  50423. break;
  50424. }
  50425. }
  50426. return this._getKeyValue(keys[keys.length - 1].value);
  50427. };
  50428. /**
  50429. * Affect the interpolated value to the target
  50430. * @param currentValue defines the value computed by the animation
  50431. * @param weight defines the weight to apply to this value
  50432. */
  50433. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50434. if (weight === void 0) { weight = 1.0; }
  50435. // Set value
  50436. var path;
  50437. var destination;
  50438. var targetPropertyPath = this._animation.targetPropertyPath;
  50439. if (targetPropertyPath.length > 1) {
  50440. var property = this._target[targetPropertyPath[0]];
  50441. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50442. property = property[targetPropertyPath[index]];
  50443. }
  50444. path = targetPropertyPath[targetPropertyPath.length - 1];
  50445. destination = property;
  50446. }
  50447. else {
  50448. path = targetPropertyPath[0];
  50449. destination = this._target;
  50450. }
  50451. this._targetPath = path;
  50452. this._activeTarget = destination;
  50453. this._weight = weight;
  50454. // Blending
  50455. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50456. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50457. if (enableBlending && this._blendingFactor <= 1.0) {
  50458. if (!this._originalBlendValue) {
  50459. var originalValue = destination[path];
  50460. if (originalValue.clone) {
  50461. this._originalBlendValue = originalValue.clone();
  50462. }
  50463. else {
  50464. this._originalBlendValue = originalValue;
  50465. }
  50466. }
  50467. }
  50468. if (weight !== -1.0) {
  50469. if (!this._originalValue) {
  50470. var originalValue = void 0;
  50471. if (destination.getRestPose) {
  50472. originalValue = destination.getRestPose();
  50473. }
  50474. else {
  50475. originalValue = destination[path];
  50476. }
  50477. if (originalValue.clone) {
  50478. this._originalValue = originalValue.clone();
  50479. }
  50480. else {
  50481. this._originalValue = originalValue;
  50482. }
  50483. }
  50484. }
  50485. if (enableBlending && this._blendingFactor <= 1.0) {
  50486. if (this._originalBlendValue.prototype) {
  50487. if (this._originalBlendValue.prototype.Lerp) {
  50488. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  50489. }
  50490. else {
  50491. this._currentValue = currentValue;
  50492. }
  50493. }
  50494. else if (this._originalBlendValue.m) {
  50495. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50496. if (this._currentValue) {
  50497. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50498. }
  50499. else {
  50500. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50501. }
  50502. }
  50503. else {
  50504. if (this._currentValue) {
  50505. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50506. }
  50507. else {
  50508. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50509. }
  50510. }
  50511. }
  50512. else {
  50513. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  50514. }
  50515. this._blendingFactor += blendingSpeed;
  50516. }
  50517. else {
  50518. this._currentValue = currentValue;
  50519. }
  50520. if (weight !== -1.0) {
  50521. this._scene._registerTargetForLateAnimationBinding(this);
  50522. }
  50523. else {
  50524. destination[path] = this._currentValue;
  50525. }
  50526. if (this._target.markAsDirty) {
  50527. this._target.markAsDirty(this._animation.targetProperty);
  50528. }
  50529. };
  50530. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50531. if (this._target && this._target.animationPropertiesOverride) {
  50532. return this._target.animationPropertiesOverride.loopMode;
  50533. }
  50534. return this._animation.loopMode;
  50535. };
  50536. /**
  50537. * Move the current animation to a given frame
  50538. * @param frame defines the frame to move to
  50539. */
  50540. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50541. var keys = this._animation.getKeys();
  50542. if (frame < keys[0].frame) {
  50543. frame = keys[0].frame;
  50544. }
  50545. else if (frame > keys[keys.length - 1].frame) {
  50546. frame = keys[keys.length - 1].frame;
  50547. }
  50548. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50549. this.setValue(currentValue, -1);
  50550. };
  50551. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50552. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50553. this._ratioOffset = this._previousRatio - newRatio;
  50554. };
  50555. /**
  50556. * Execute the current animation
  50557. * @param delay defines the delay to add to the current frame
  50558. * @param from defines the lower bound of the animation range
  50559. * @param to defines the upper bound of the animation range
  50560. * @param loop defines if the current animation must loop
  50561. * @param speedRatio defines the current speed ratio
  50562. * @param weight defines the weight of the animation (default is -1 so no weight)
  50563. * @returns a boolean indicating if the animation has ended
  50564. */
  50565. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50566. if (weight === void 0) { weight = -1.0; }
  50567. var targetPropertyPath = this._animation.targetPropertyPath;
  50568. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50569. this._stopped = true;
  50570. return false;
  50571. }
  50572. var returnValue = true;
  50573. var keys = this._animation.getKeys();
  50574. // Adding a start key at frame 0 if missing
  50575. if (keys[0].frame !== 0) {
  50576. var newKey = { frame: 0, value: keys[0].value };
  50577. keys.splice(0, 0, newKey);
  50578. }
  50579. // Check limits
  50580. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50581. from = keys[0].frame;
  50582. }
  50583. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50584. to = keys[keys.length - 1].frame;
  50585. }
  50586. //to and from cannot be the same key
  50587. if (from === to) {
  50588. if (from > keys[0].frame) {
  50589. from--;
  50590. }
  50591. else if (to < keys[keys.length - 1].frame) {
  50592. to++;
  50593. }
  50594. }
  50595. // Compute ratio
  50596. var range = to - from;
  50597. var offsetValue;
  50598. // ratio represents the frame delta between from and to
  50599. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50600. var highLimitValue = 0;
  50601. this._previousDelay = delay;
  50602. this._previousRatio = ratio;
  50603. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  50604. returnValue = false;
  50605. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  50606. }
  50607. else {
  50608. // Get max value if required
  50609. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50610. var keyOffset = to.toString() + from.toString();
  50611. if (!this._offsetsCache[keyOffset]) {
  50612. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50613. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50614. switch (this._animation.dataType) {
  50615. // Float
  50616. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50617. this._offsetsCache[keyOffset] = toValue - fromValue;
  50618. break;
  50619. // Quaternion
  50620. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50621. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50622. break;
  50623. // Vector3
  50624. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50625. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50626. // Vector2
  50627. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50628. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50629. // Size
  50630. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50631. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50632. // Color3
  50633. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50634. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50635. default:
  50636. break;
  50637. }
  50638. this._highLimitsCache[keyOffset] = toValue;
  50639. }
  50640. highLimitValue = this._highLimitsCache[keyOffset];
  50641. offsetValue = this._offsetsCache[keyOffset];
  50642. }
  50643. }
  50644. if (offsetValue === undefined) {
  50645. switch (this._animation.dataType) {
  50646. // Float
  50647. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50648. offsetValue = 0;
  50649. break;
  50650. // Quaternion
  50651. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50652. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50653. break;
  50654. // Vector3
  50655. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50656. offsetValue = BABYLON.Vector3.Zero();
  50657. break;
  50658. // Vector2
  50659. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50660. offsetValue = BABYLON.Vector2.Zero();
  50661. break;
  50662. // Size
  50663. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50664. offsetValue = BABYLON.Size.Zero();
  50665. break;
  50666. // Color3
  50667. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50668. offsetValue = BABYLON.Color3.Black();
  50669. }
  50670. }
  50671. // Compute value
  50672. var repeatCount = (ratio / range) >> 0;
  50673. var currentFrame = returnValue ? from + ratio % range : to;
  50674. // Need to normalize?
  50675. if (this._host && this._host.syncRoot) {
  50676. var syncRoot = this._host.syncRoot;
  50677. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  50678. currentFrame = from + (to - from) * hostNormalizedFrame;
  50679. }
  50680. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  50681. // Set value
  50682. this.setValue(currentValue, weight);
  50683. // Check events
  50684. var events = this._animation.getEvents();
  50685. for (var index = 0; index < events.length; index++) {
  50686. // Make sure current frame has passed event frame and that event frame is within the current range
  50687. // Also, handle both forward and reverse animations
  50688. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  50689. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  50690. var event = events[index];
  50691. if (!event.isDone) {
  50692. // If event should be done only once, remove it.
  50693. if (event.onlyOnce) {
  50694. events.splice(index, 1);
  50695. index--;
  50696. }
  50697. event.isDone = true;
  50698. event.action();
  50699. } // Don't do anything if the event has already be done.
  50700. }
  50701. else if (events[index].isDone && !events[index].onlyOnce) {
  50702. // reset event, the animation is looping
  50703. events[index].isDone = false;
  50704. }
  50705. }
  50706. if (!returnValue) {
  50707. this._stopped = true;
  50708. }
  50709. return returnValue;
  50710. };
  50711. return RuntimeAnimation;
  50712. }());
  50713. BABYLON.RuntimeAnimation = RuntimeAnimation;
  50714. })(BABYLON || (BABYLON = {}));
  50715. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  50716. "use strict";
  50717. var BABYLON;
  50718. (function (BABYLON) {
  50719. var Animatable = /** @class */ (function () {
  50720. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  50721. if (fromFrame === void 0) { fromFrame = 0; }
  50722. if (toFrame === void 0) { toFrame = 100; }
  50723. if (loopAnimation === void 0) { loopAnimation = false; }
  50724. if (speedRatio === void 0) { speedRatio = 1.0; }
  50725. this.target = target;
  50726. this.fromFrame = fromFrame;
  50727. this.toFrame = toFrame;
  50728. this.loopAnimation = loopAnimation;
  50729. this.onAnimationEnd = onAnimationEnd;
  50730. this._localDelayOffset = null;
  50731. this._pausedDelay = null;
  50732. this._runtimeAnimations = new Array();
  50733. this._paused = false;
  50734. this._speedRatio = 1;
  50735. this._weight = -1.0;
  50736. this.animationStarted = false;
  50737. if (animations) {
  50738. this.appendAnimations(target, animations);
  50739. }
  50740. this._speedRatio = speedRatio;
  50741. this._scene = scene;
  50742. scene._activeAnimatables.push(this);
  50743. }
  50744. Object.defineProperty(Animatable.prototype, "syncRoot", {
  50745. /**
  50746. * Gets the root Animatable used to synchronize and normalize animations
  50747. */
  50748. get: function () {
  50749. return this._syncRoot;
  50750. },
  50751. enumerable: true,
  50752. configurable: true
  50753. });
  50754. Object.defineProperty(Animatable.prototype, "masterFrame", {
  50755. /**
  50756. * Gets the current frame of the first RuntimeAnimation
  50757. * Used to synchronize Animatables
  50758. */
  50759. get: function () {
  50760. if (this._runtimeAnimations.length === 0) {
  50761. return 0;
  50762. }
  50763. return this._runtimeAnimations[0].currentFrame;
  50764. },
  50765. enumerable: true,
  50766. configurable: true
  50767. });
  50768. Object.defineProperty(Animatable.prototype, "weight", {
  50769. /**
  50770. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  50771. */
  50772. get: function () {
  50773. return this._weight;
  50774. },
  50775. set: function (value) {
  50776. if (value === -1) {
  50777. this._weight = -1;
  50778. return;
  50779. }
  50780. // Else weight must be in [0, 1] range
  50781. this._weight = Math.min(Math.max(value, 0), 1.0);
  50782. },
  50783. enumerable: true,
  50784. configurable: true
  50785. });
  50786. Object.defineProperty(Animatable.prototype, "speedRatio", {
  50787. /**
  50788. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  50789. */
  50790. get: function () {
  50791. return this._speedRatio;
  50792. },
  50793. set: function (value) {
  50794. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  50795. var animation = this._runtimeAnimations[index];
  50796. animation._prepareForSpeedRatioChange(value);
  50797. }
  50798. this._speedRatio = value;
  50799. },
  50800. enumerable: true,
  50801. configurable: true
  50802. });
  50803. // Methods
  50804. /**
  50805. * Synchronize and normalize current Animatable with a source Animatable.
  50806. * This is useful when using animation weights and when animations are not of the same length
  50807. * @param root defines the root Animatable to synchronize with
  50808. * @returns the current Animatable
  50809. */
  50810. Animatable.prototype.syncWith = function (root) {
  50811. this._syncRoot = root;
  50812. if (root) {
  50813. // Make sure this animatable will animate after the root
  50814. var index = this._scene._activeAnimatables.indexOf(this);
  50815. if (index > -1) {
  50816. this._scene._activeAnimatables.splice(index, 1);
  50817. this._scene._activeAnimatables.push(this);
  50818. }
  50819. }
  50820. return this;
  50821. };
  50822. Animatable.prototype.getAnimations = function () {
  50823. return this._runtimeAnimations;
  50824. };
  50825. Animatable.prototype.appendAnimations = function (target, animations) {
  50826. for (var index = 0; index < animations.length; index++) {
  50827. var animation = animations[index];
  50828. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  50829. }
  50830. };
  50831. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  50832. var runtimeAnimations = this._runtimeAnimations;
  50833. for (var index = 0; index < runtimeAnimations.length; index++) {
  50834. if (runtimeAnimations[index].animation.targetProperty === property) {
  50835. return runtimeAnimations[index].animation;
  50836. }
  50837. }
  50838. return null;
  50839. };
  50840. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  50841. var runtimeAnimations = this._runtimeAnimations;
  50842. for (var index = 0; index < runtimeAnimations.length; index++) {
  50843. if (runtimeAnimations[index].animation.targetProperty === property) {
  50844. return runtimeAnimations[index];
  50845. }
  50846. }
  50847. return null;
  50848. };
  50849. Animatable.prototype.reset = function () {
  50850. var runtimeAnimations = this._runtimeAnimations;
  50851. for (var index = 0; index < runtimeAnimations.length; index++) {
  50852. runtimeAnimations[index].reset();
  50853. }
  50854. // Reset to original value
  50855. for (index = 0; index < runtimeAnimations.length; index++) {
  50856. var animation = runtimeAnimations[index];
  50857. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  50858. }
  50859. this._localDelayOffset = null;
  50860. this._pausedDelay = null;
  50861. };
  50862. Animatable.prototype.enableBlending = function (blendingSpeed) {
  50863. var runtimeAnimations = this._runtimeAnimations;
  50864. for (var index = 0; index < runtimeAnimations.length; index++) {
  50865. runtimeAnimations[index].animation.enableBlending = true;
  50866. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  50867. }
  50868. };
  50869. Animatable.prototype.disableBlending = function () {
  50870. var runtimeAnimations = this._runtimeAnimations;
  50871. for (var index = 0; index < runtimeAnimations.length; index++) {
  50872. runtimeAnimations[index].animation.enableBlending = false;
  50873. }
  50874. };
  50875. Animatable.prototype.goToFrame = function (frame) {
  50876. var runtimeAnimations = this._runtimeAnimations;
  50877. if (runtimeAnimations[0]) {
  50878. var fps = runtimeAnimations[0].animation.framePerSecond;
  50879. var currentFrame = runtimeAnimations[0].currentFrame;
  50880. var adjustTime = frame - currentFrame;
  50881. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  50882. if (this._localDelayOffset === null) {
  50883. this._localDelayOffset = 0;
  50884. }
  50885. this._localDelayOffset -= delay;
  50886. }
  50887. for (var index = 0; index < runtimeAnimations.length; index++) {
  50888. runtimeAnimations[index].goToFrame(frame);
  50889. }
  50890. };
  50891. Animatable.prototype.pause = function () {
  50892. if (this._paused) {
  50893. return;
  50894. }
  50895. this._paused = true;
  50896. };
  50897. Animatable.prototype.restart = function () {
  50898. this._paused = false;
  50899. };
  50900. Animatable.prototype.stop = function (animationName) {
  50901. if (animationName) {
  50902. var idx = this._scene._activeAnimatables.indexOf(this);
  50903. if (idx > -1) {
  50904. var runtimeAnimations = this._runtimeAnimations;
  50905. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  50906. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  50907. continue;
  50908. }
  50909. runtimeAnimations[index].dispose();
  50910. runtimeAnimations.splice(index, 1);
  50911. }
  50912. if (runtimeAnimations.length == 0) {
  50913. this._scene._activeAnimatables.splice(idx, 1);
  50914. if (this.onAnimationEnd) {
  50915. this.onAnimationEnd();
  50916. }
  50917. }
  50918. }
  50919. }
  50920. else {
  50921. var index = this._scene._activeAnimatables.indexOf(this);
  50922. if (index > -1) {
  50923. this._scene._activeAnimatables.splice(index, 1);
  50924. var runtimeAnimations = this._runtimeAnimations;
  50925. for (var index = 0; index < runtimeAnimations.length; index++) {
  50926. runtimeAnimations[index].dispose();
  50927. }
  50928. if (this.onAnimationEnd) {
  50929. this.onAnimationEnd();
  50930. }
  50931. }
  50932. }
  50933. };
  50934. Animatable.prototype._animate = function (delay) {
  50935. if (this._paused) {
  50936. this.animationStarted = false;
  50937. if (this._pausedDelay === null) {
  50938. this._pausedDelay = delay;
  50939. }
  50940. return true;
  50941. }
  50942. if (this._localDelayOffset === null) {
  50943. this._localDelayOffset = delay;
  50944. this._pausedDelay = null;
  50945. }
  50946. else if (this._pausedDelay !== null) {
  50947. this._localDelayOffset += delay - this._pausedDelay;
  50948. this._pausedDelay = null;
  50949. }
  50950. if (this._weight === 0) {
  50951. return true;
  50952. }
  50953. // Animating
  50954. var running = false;
  50955. var runtimeAnimations = this._runtimeAnimations;
  50956. var index;
  50957. for (index = 0; index < runtimeAnimations.length; index++) {
  50958. var animation = runtimeAnimations[index];
  50959. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  50960. running = running || isRunning;
  50961. }
  50962. this.animationStarted = running;
  50963. if (!running) {
  50964. // Remove from active animatables
  50965. index = this._scene._activeAnimatables.indexOf(this);
  50966. this._scene._activeAnimatables.splice(index, 1);
  50967. // Dispose all runtime animations
  50968. for (index = 0; index < runtimeAnimations.length; index++) {
  50969. runtimeAnimations[index].dispose();
  50970. }
  50971. }
  50972. if (!running && this.onAnimationEnd) {
  50973. this.onAnimationEnd();
  50974. this.onAnimationEnd = null;
  50975. }
  50976. return running;
  50977. };
  50978. return Animatable;
  50979. }());
  50980. BABYLON.Animatable = Animatable;
  50981. })(BABYLON || (BABYLON = {}));
  50982. //# sourceMappingURL=babylon.animatable.js.map
  50983. "use strict";
  50984. var BABYLON;
  50985. (function (BABYLON) {
  50986. var EasingFunction = /** @class */ (function () {
  50987. function EasingFunction() {
  50988. // Properties
  50989. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  50990. }
  50991. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  50992. get: function () {
  50993. return EasingFunction._EASINGMODE_EASEIN;
  50994. },
  50995. enumerable: true,
  50996. configurable: true
  50997. });
  50998. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  50999. get: function () {
  51000. return EasingFunction._EASINGMODE_EASEOUT;
  51001. },
  51002. enumerable: true,
  51003. configurable: true
  51004. });
  51005. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51006. get: function () {
  51007. return EasingFunction._EASINGMODE_EASEINOUT;
  51008. },
  51009. enumerable: true,
  51010. configurable: true
  51011. });
  51012. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51013. var n = Math.min(Math.max(easingMode, 0), 2);
  51014. this._easingMode = n;
  51015. };
  51016. EasingFunction.prototype.getEasingMode = function () {
  51017. return this._easingMode;
  51018. };
  51019. EasingFunction.prototype.easeInCore = function (gradient) {
  51020. throw new Error('You must implement this method');
  51021. };
  51022. EasingFunction.prototype.ease = function (gradient) {
  51023. switch (this._easingMode) {
  51024. case EasingFunction.EASINGMODE_EASEIN:
  51025. return this.easeInCore(gradient);
  51026. case EasingFunction.EASINGMODE_EASEOUT:
  51027. return (1 - this.easeInCore(1 - gradient));
  51028. }
  51029. if (gradient >= 0.5) {
  51030. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51031. }
  51032. return (this.easeInCore(gradient * 2) * 0.5);
  51033. };
  51034. //Statics
  51035. EasingFunction._EASINGMODE_EASEIN = 0;
  51036. EasingFunction._EASINGMODE_EASEOUT = 1;
  51037. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51038. return EasingFunction;
  51039. }());
  51040. BABYLON.EasingFunction = EasingFunction;
  51041. var CircleEase = /** @class */ (function (_super) {
  51042. __extends(CircleEase, _super);
  51043. function CircleEase() {
  51044. return _super !== null && _super.apply(this, arguments) || this;
  51045. }
  51046. CircleEase.prototype.easeInCore = function (gradient) {
  51047. gradient = Math.max(0, Math.min(1, gradient));
  51048. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51049. };
  51050. return CircleEase;
  51051. }(EasingFunction));
  51052. BABYLON.CircleEase = CircleEase;
  51053. var BackEase = /** @class */ (function (_super) {
  51054. __extends(BackEase, _super);
  51055. function BackEase(amplitude) {
  51056. if (amplitude === void 0) { amplitude = 1; }
  51057. var _this = _super.call(this) || this;
  51058. _this.amplitude = amplitude;
  51059. return _this;
  51060. }
  51061. BackEase.prototype.easeInCore = function (gradient) {
  51062. var num = Math.max(0, this.amplitude);
  51063. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51064. };
  51065. return BackEase;
  51066. }(EasingFunction));
  51067. BABYLON.BackEase = BackEase;
  51068. var BounceEase = /** @class */ (function (_super) {
  51069. __extends(BounceEase, _super);
  51070. function BounceEase(bounces, bounciness) {
  51071. if (bounces === void 0) { bounces = 3; }
  51072. if (bounciness === void 0) { bounciness = 2; }
  51073. var _this = _super.call(this) || this;
  51074. _this.bounces = bounces;
  51075. _this.bounciness = bounciness;
  51076. return _this;
  51077. }
  51078. BounceEase.prototype.easeInCore = function (gradient) {
  51079. var y = Math.max(0.0, this.bounces);
  51080. var bounciness = this.bounciness;
  51081. if (bounciness <= 1.0) {
  51082. bounciness = 1.001;
  51083. }
  51084. var num9 = Math.pow(bounciness, y);
  51085. var num5 = 1.0 - bounciness;
  51086. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51087. var num15 = gradient * num4;
  51088. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51089. var num3 = Math.floor(num65);
  51090. var num13 = num3 + 1.0;
  51091. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51092. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51093. var num7 = (num8 + num12) * 0.5;
  51094. var num6 = gradient - num7;
  51095. var num2 = num7 - num8;
  51096. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51097. };
  51098. return BounceEase;
  51099. }(EasingFunction));
  51100. BABYLON.BounceEase = BounceEase;
  51101. var CubicEase = /** @class */ (function (_super) {
  51102. __extends(CubicEase, _super);
  51103. function CubicEase() {
  51104. return _super !== null && _super.apply(this, arguments) || this;
  51105. }
  51106. CubicEase.prototype.easeInCore = function (gradient) {
  51107. return (gradient * gradient * gradient);
  51108. };
  51109. return CubicEase;
  51110. }(EasingFunction));
  51111. BABYLON.CubicEase = CubicEase;
  51112. var ElasticEase = /** @class */ (function (_super) {
  51113. __extends(ElasticEase, _super);
  51114. function ElasticEase(oscillations, springiness) {
  51115. if (oscillations === void 0) { oscillations = 3; }
  51116. if (springiness === void 0) { springiness = 3; }
  51117. var _this = _super.call(this) || this;
  51118. _this.oscillations = oscillations;
  51119. _this.springiness = springiness;
  51120. return _this;
  51121. }
  51122. ElasticEase.prototype.easeInCore = function (gradient) {
  51123. var num2;
  51124. var num3 = Math.max(0.0, this.oscillations);
  51125. var num = Math.max(0.0, this.springiness);
  51126. if (num == 0) {
  51127. num2 = gradient;
  51128. }
  51129. else {
  51130. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51131. }
  51132. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51133. };
  51134. return ElasticEase;
  51135. }(EasingFunction));
  51136. BABYLON.ElasticEase = ElasticEase;
  51137. var ExponentialEase = /** @class */ (function (_super) {
  51138. __extends(ExponentialEase, _super);
  51139. function ExponentialEase(exponent) {
  51140. if (exponent === void 0) { exponent = 2; }
  51141. var _this = _super.call(this) || this;
  51142. _this.exponent = exponent;
  51143. return _this;
  51144. }
  51145. ExponentialEase.prototype.easeInCore = function (gradient) {
  51146. if (this.exponent <= 0) {
  51147. return gradient;
  51148. }
  51149. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51150. };
  51151. return ExponentialEase;
  51152. }(EasingFunction));
  51153. BABYLON.ExponentialEase = ExponentialEase;
  51154. var PowerEase = /** @class */ (function (_super) {
  51155. __extends(PowerEase, _super);
  51156. function PowerEase(power) {
  51157. if (power === void 0) { power = 2; }
  51158. var _this = _super.call(this) || this;
  51159. _this.power = power;
  51160. return _this;
  51161. }
  51162. PowerEase.prototype.easeInCore = function (gradient) {
  51163. var y = Math.max(0.0, this.power);
  51164. return Math.pow(gradient, y);
  51165. };
  51166. return PowerEase;
  51167. }(EasingFunction));
  51168. BABYLON.PowerEase = PowerEase;
  51169. var QuadraticEase = /** @class */ (function (_super) {
  51170. __extends(QuadraticEase, _super);
  51171. function QuadraticEase() {
  51172. return _super !== null && _super.apply(this, arguments) || this;
  51173. }
  51174. QuadraticEase.prototype.easeInCore = function (gradient) {
  51175. return (gradient * gradient);
  51176. };
  51177. return QuadraticEase;
  51178. }(EasingFunction));
  51179. BABYLON.QuadraticEase = QuadraticEase;
  51180. var QuarticEase = /** @class */ (function (_super) {
  51181. __extends(QuarticEase, _super);
  51182. function QuarticEase() {
  51183. return _super !== null && _super.apply(this, arguments) || this;
  51184. }
  51185. QuarticEase.prototype.easeInCore = function (gradient) {
  51186. return (gradient * gradient * gradient * gradient);
  51187. };
  51188. return QuarticEase;
  51189. }(EasingFunction));
  51190. BABYLON.QuarticEase = QuarticEase;
  51191. var QuinticEase = /** @class */ (function (_super) {
  51192. __extends(QuinticEase, _super);
  51193. function QuinticEase() {
  51194. return _super !== null && _super.apply(this, arguments) || this;
  51195. }
  51196. QuinticEase.prototype.easeInCore = function (gradient) {
  51197. return (gradient * gradient * gradient * gradient * gradient);
  51198. };
  51199. return QuinticEase;
  51200. }(EasingFunction));
  51201. BABYLON.QuinticEase = QuinticEase;
  51202. var SineEase = /** @class */ (function (_super) {
  51203. __extends(SineEase, _super);
  51204. function SineEase() {
  51205. return _super !== null && _super.apply(this, arguments) || this;
  51206. }
  51207. SineEase.prototype.easeInCore = function (gradient) {
  51208. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51209. };
  51210. return SineEase;
  51211. }(EasingFunction));
  51212. BABYLON.SineEase = SineEase;
  51213. var BezierCurveEase = /** @class */ (function (_super) {
  51214. __extends(BezierCurveEase, _super);
  51215. function BezierCurveEase(x1, y1, x2, y2) {
  51216. if (x1 === void 0) { x1 = 0; }
  51217. if (y1 === void 0) { y1 = 0; }
  51218. if (x2 === void 0) { x2 = 1; }
  51219. if (y2 === void 0) { y2 = 1; }
  51220. var _this = _super.call(this) || this;
  51221. _this.x1 = x1;
  51222. _this.y1 = y1;
  51223. _this.x2 = x2;
  51224. _this.y2 = y2;
  51225. return _this;
  51226. }
  51227. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51228. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51229. };
  51230. return BezierCurveEase;
  51231. }(EasingFunction));
  51232. BABYLON.BezierCurveEase = BezierCurveEase;
  51233. })(BABYLON || (BABYLON = {}));
  51234. //# sourceMappingURL=babylon.easing.js.map
  51235. "use strict";
  51236. var BABYLON;
  51237. (function (BABYLON) {
  51238. /**
  51239. * A Condition applied to an Action
  51240. */
  51241. var Condition = /** @class */ (function () {
  51242. /**
  51243. * Creates a new Condition
  51244. * @param actionManager the manager of the action the condition is applied to
  51245. */
  51246. function Condition(actionManager) {
  51247. this._actionManager = actionManager;
  51248. }
  51249. /**
  51250. * Check if the current condition is valid
  51251. * @returns a boolean
  51252. */
  51253. Condition.prototype.isValid = function () {
  51254. return true;
  51255. };
  51256. /**
  51257. * Internal only
  51258. * @ignore
  51259. */
  51260. Condition.prototype._getProperty = function (propertyPath) {
  51261. return this._actionManager._getProperty(propertyPath);
  51262. };
  51263. /**
  51264. * Internal only
  51265. * @ignore
  51266. */
  51267. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51268. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51269. };
  51270. /**
  51271. * Serialize placeholder for child classes
  51272. * @returns the serialized object
  51273. */
  51274. Condition.prototype.serialize = function () {
  51275. };
  51276. /**
  51277. * Internal only
  51278. * @ignore
  51279. */
  51280. Condition.prototype._serialize = function (serializedCondition) {
  51281. return {
  51282. type: 2,
  51283. children: [],
  51284. name: serializedCondition.name,
  51285. properties: serializedCondition.properties
  51286. };
  51287. };
  51288. return Condition;
  51289. }());
  51290. BABYLON.Condition = Condition;
  51291. /**
  51292. * Defines specific conditional operators as extensions of Condition
  51293. */
  51294. var ValueCondition = /** @class */ (function (_super) {
  51295. __extends(ValueCondition, _super);
  51296. /**
  51297. * Creates a new ValueCondition
  51298. * @param actionManager manager for the action the condition applies to
  51299. * @param target for the action
  51300. * @param propertyPath path to specify the property of the target the conditional operator uses
  51301. * @param value the vale compared by the conditional operator against the current value of the property
  51302. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  51303. */
  51304. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  51305. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51306. var _this = _super.call(this, actionManager) || this;
  51307. _this.propertyPath = propertyPath;
  51308. _this.value = value;
  51309. _this.operator = operator;
  51310. _this._target = target;
  51311. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51312. _this._property = _this._getProperty(_this.propertyPath);
  51313. return _this;
  51314. }
  51315. Object.defineProperty(ValueCondition, "IsEqual", {
  51316. /**
  51317. * returns the number for IsEqual
  51318. */
  51319. get: function () {
  51320. return ValueCondition._IsEqual;
  51321. },
  51322. enumerable: true,
  51323. configurable: true
  51324. });
  51325. Object.defineProperty(ValueCondition, "IsDifferent", {
  51326. /**
  51327. * Returns the number for IsDifferent
  51328. */
  51329. get: function () {
  51330. return ValueCondition._IsDifferent;
  51331. },
  51332. enumerable: true,
  51333. configurable: true
  51334. });
  51335. Object.defineProperty(ValueCondition, "IsGreater", {
  51336. /**
  51337. * Returns the number for IsGreater
  51338. */
  51339. get: function () {
  51340. return ValueCondition._IsGreater;
  51341. },
  51342. enumerable: true,
  51343. configurable: true
  51344. });
  51345. Object.defineProperty(ValueCondition, "IsLesser", {
  51346. /**
  51347. * Returns the number for IsLesser
  51348. */
  51349. get: function () {
  51350. return ValueCondition._IsLesser;
  51351. },
  51352. enumerable: true,
  51353. configurable: true
  51354. });
  51355. /**
  51356. * Compares the given value with the property value for the specified conditional operator
  51357. * @returns the result of the comparison
  51358. */
  51359. ValueCondition.prototype.isValid = function () {
  51360. switch (this.operator) {
  51361. case ValueCondition.IsGreater:
  51362. return this._effectiveTarget[this._property] > this.value;
  51363. case ValueCondition.IsLesser:
  51364. return this._effectiveTarget[this._property] < this.value;
  51365. case ValueCondition.IsEqual:
  51366. case ValueCondition.IsDifferent:
  51367. var check;
  51368. if (this.value.equals) {
  51369. check = this.value.equals(this._effectiveTarget[this._property]);
  51370. }
  51371. else {
  51372. check = this.value === this._effectiveTarget[this._property];
  51373. }
  51374. return this.operator === ValueCondition.IsEqual ? check : !check;
  51375. }
  51376. return false;
  51377. };
  51378. /**
  51379. * Serialize the ValueCondition into a JSON compatible object
  51380. * @returns serialization object
  51381. */
  51382. ValueCondition.prototype.serialize = function () {
  51383. return this._serialize({
  51384. name: "ValueCondition",
  51385. properties: [
  51386. BABYLON.Action._GetTargetProperty(this._target),
  51387. { name: "propertyPath", value: this.propertyPath },
  51388. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51389. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51390. ]
  51391. });
  51392. };
  51393. /**
  51394. * Gets the name of the conditional operator for the ValueCondition
  51395. * @param operator the conditional operator
  51396. * @returns the name
  51397. */
  51398. ValueCondition.GetOperatorName = function (operator) {
  51399. switch (operator) {
  51400. case ValueCondition._IsEqual: return "IsEqual";
  51401. case ValueCondition._IsDifferent: return "IsDifferent";
  51402. case ValueCondition._IsGreater: return "IsGreater";
  51403. case ValueCondition._IsLesser: return "IsLesser";
  51404. default: return "";
  51405. }
  51406. };
  51407. /**
  51408. * Internal only
  51409. * @ignore
  51410. */
  51411. ValueCondition._IsEqual = 0;
  51412. /**
  51413. * Internal only
  51414. * @ignore
  51415. */
  51416. ValueCondition._IsDifferent = 1;
  51417. /**
  51418. * Internal only
  51419. * @ignore
  51420. */
  51421. ValueCondition._IsGreater = 2;
  51422. /**
  51423. * Internal only
  51424. * @ignore
  51425. */
  51426. ValueCondition._IsLesser = 3;
  51427. return ValueCondition;
  51428. }(Condition));
  51429. BABYLON.ValueCondition = ValueCondition;
  51430. /**
  51431. * Defines a predicate condition as an extension of Condition
  51432. */
  51433. var PredicateCondition = /** @class */ (function (_super) {
  51434. __extends(PredicateCondition, _super);
  51435. /**
  51436. * Creates a new {BABYLON.PredicateCondition}
  51437. * @param actionManager manager for the action the condition applies to
  51438. * @param predicate
  51439. */
  51440. function PredicateCondition(actionManager, predicate) {
  51441. var _this = _super.call(this, actionManager) || this;
  51442. _this.predicate = predicate;
  51443. return _this;
  51444. }
  51445. /**
  51446. * @returns the validity of the predicate condition
  51447. */
  51448. PredicateCondition.prototype.isValid = function () {
  51449. return this.predicate();
  51450. };
  51451. return PredicateCondition;
  51452. }(Condition));
  51453. BABYLON.PredicateCondition = PredicateCondition;
  51454. /**
  51455. * Defines a state condition as an extension of {BABYLON.Condition}
  51456. */
  51457. var StateCondition = /** @class */ (function (_super) {
  51458. __extends(StateCondition, _super);
  51459. /**
  51460. * Creates a new {BABYLON.StateCondition}
  51461. * @param actionManager manager for the action the condition applies to
  51462. * @param target of the condition
  51463. * @param value to compare with target state
  51464. */
  51465. function StateCondition(actionManager, target, value) {
  51466. var _this = _super.call(this, actionManager) || this;
  51467. _this.value = value;
  51468. _this._target = target;
  51469. return _this;
  51470. }
  51471. /**
  51472. * @returns the validity of the state
  51473. */
  51474. StateCondition.prototype.isValid = function () {
  51475. return this._target.state === this.value;
  51476. };
  51477. /**
  51478. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  51479. * @returns serialization object
  51480. */
  51481. StateCondition.prototype.serialize = function () {
  51482. return this._serialize({
  51483. name: "StateCondition",
  51484. properties: [
  51485. BABYLON.Action._GetTargetProperty(this._target),
  51486. { name: "value", value: this.value }
  51487. ]
  51488. });
  51489. };
  51490. return StateCondition;
  51491. }(Condition));
  51492. BABYLON.StateCondition = StateCondition;
  51493. })(BABYLON || (BABYLON = {}));
  51494. //# sourceMappingURL=babylon.condition.js.map
  51495. "use strict";
  51496. var BABYLON;
  51497. (function (BABYLON) {
  51498. /**
  51499. * The action to be carried out following a trigger
  51500. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51501. */
  51502. var Action = /** @class */ (function () {
  51503. /**
  51504. * Creates a new Action
  51505. * @param triggerOptions the trigger, with or without parameters, for the action
  51506. * @param condition an optional determinant of action
  51507. */
  51508. function Action(triggerOptions, condition) {
  51509. this.triggerOptions = triggerOptions;
  51510. /**
  51511. * An event triggered prior to action being executed.
  51512. */
  51513. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51514. if (triggerOptions.parameter) {
  51515. this.trigger = triggerOptions.trigger;
  51516. this._triggerParameter = triggerOptions.parameter;
  51517. }
  51518. else {
  51519. this.trigger = triggerOptions;
  51520. }
  51521. this._nextActiveAction = this;
  51522. this._condition = condition;
  51523. }
  51524. /**
  51525. * Internal only
  51526. * @ignore
  51527. */
  51528. Action.prototype._prepare = function () {
  51529. };
  51530. /**
  51531. * Gets the trigger parameters
  51532. * @returns the trigger parameters
  51533. */
  51534. Action.prototype.getTriggerParameter = function () {
  51535. return this._triggerParameter;
  51536. };
  51537. /**
  51538. * Internal only - executes current action event
  51539. * @ignore
  51540. */
  51541. Action.prototype._executeCurrent = function (evt) {
  51542. if (this._nextActiveAction._condition) {
  51543. var condition = this._nextActiveAction._condition;
  51544. var currentRenderId = this._actionManager.getScene().getRenderId();
  51545. // We cache the current evaluation for the current frame
  51546. if (condition._evaluationId === currentRenderId) {
  51547. if (!condition._currentResult) {
  51548. return;
  51549. }
  51550. }
  51551. else {
  51552. condition._evaluationId = currentRenderId;
  51553. if (!condition.isValid()) {
  51554. condition._currentResult = false;
  51555. return;
  51556. }
  51557. condition._currentResult = true;
  51558. }
  51559. }
  51560. this.onBeforeExecuteObservable.notifyObservers(this);
  51561. this._nextActiveAction.execute(evt);
  51562. this.skipToNextActiveAction();
  51563. };
  51564. /**
  51565. * Execute placeholder for child classes
  51566. * @param evt optional action event
  51567. */
  51568. Action.prototype.execute = function (evt) {
  51569. };
  51570. /**
  51571. * Skips to next active action
  51572. */
  51573. Action.prototype.skipToNextActiveAction = function () {
  51574. if (this._nextActiveAction._child) {
  51575. if (!this._nextActiveAction._child._actionManager) {
  51576. this._nextActiveAction._child._actionManager = this._actionManager;
  51577. }
  51578. this._nextActiveAction = this._nextActiveAction._child;
  51579. }
  51580. else {
  51581. this._nextActiveAction = this;
  51582. }
  51583. };
  51584. /**
  51585. * Adds action to chain of actions, may be a DoNothingAction
  51586. * @param index The index of the attribute.
  51587. * @returns The action passed in
  51588. * @see https://www.babylonjs-playground.com/#1T30HR#0
  51589. */
  51590. Action.prototype.then = function (action) {
  51591. this._child = action;
  51592. action._actionManager = this._actionManager;
  51593. action._prepare();
  51594. return action;
  51595. };
  51596. /**
  51597. * Internal only
  51598. * @ignore
  51599. */
  51600. Action.prototype._getProperty = function (propertyPath) {
  51601. return this._actionManager._getProperty(propertyPath);
  51602. };
  51603. /**
  51604. * Internal only
  51605. * @ignore
  51606. */
  51607. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  51608. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51609. };
  51610. /**
  51611. * Serialize placeholder for child classes
  51612. * @param parent of child
  51613. * @returns the serialized object
  51614. */
  51615. Action.prototype.serialize = function (parent) {
  51616. };
  51617. /**
  51618. * Internal only called by serialize
  51619. * @ignore
  51620. */
  51621. Action.prototype._serialize = function (serializedAction, parent) {
  51622. var serializationObject = {
  51623. type: 1,
  51624. children: [],
  51625. name: serializedAction.name,
  51626. properties: serializedAction.properties || []
  51627. };
  51628. // Serialize child
  51629. if (this._child) {
  51630. this._child.serialize(serializationObject);
  51631. }
  51632. // Check if "this" has a condition
  51633. if (this._condition) {
  51634. var serializedCondition = this._condition.serialize();
  51635. serializedCondition.children.push(serializationObject);
  51636. if (parent) {
  51637. parent.children.push(serializedCondition);
  51638. }
  51639. return serializedCondition;
  51640. }
  51641. if (parent) {
  51642. parent.children.push(serializationObject);
  51643. }
  51644. return serializationObject;
  51645. };
  51646. /**
  51647. * Internal only
  51648. * @ignore
  51649. */
  51650. Action._SerializeValueAsString = function (value) {
  51651. if (typeof value === "number") {
  51652. return value.toString();
  51653. }
  51654. if (typeof value === "boolean") {
  51655. return value ? "true" : "false";
  51656. }
  51657. if (value instanceof BABYLON.Vector2) {
  51658. return value.x + ", " + value.y;
  51659. }
  51660. if (value instanceof BABYLON.Vector3) {
  51661. return value.x + ", " + value.y + ", " + value.z;
  51662. }
  51663. if (value instanceof BABYLON.Color3) {
  51664. return value.r + ", " + value.g + ", " + value.b;
  51665. }
  51666. if (value instanceof BABYLON.Color4) {
  51667. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  51668. }
  51669. return value; // string
  51670. };
  51671. /**
  51672. * Internal only
  51673. * @ignore
  51674. */
  51675. Action._GetTargetProperty = function (target) {
  51676. return {
  51677. name: "target",
  51678. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  51679. : target instanceof BABYLON.Light ? "LightProperties"
  51680. : target instanceof BABYLON.Camera ? "CameraProperties"
  51681. : "SceneProperties",
  51682. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  51683. };
  51684. };
  51685. return Action;
  51686. }());
  51687. BABYLON.Action = Action;
  51688. })(BABYLON || (BABYLON = {}));
  51689. //# sourceMappingURL=babylon.action.js.map
  51690. "use strict";
  51691. var BABYLON;
  51692. (function (BABYLON) {
  51693. /**
  51694. * ActionEvent is the event being sent when an action is triggered.
  51695. */
  51696. var ActionEvent = /** @class */ (function () {
  51697. /**
  51698. * @param source The mesh or sprite that triggered the action.
  51699. * @param pointerX The X mouse cursor position at the time of the event
  51700. * @param pointerY The Y mouse cursor position at the time of the event
  51701. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  51702. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  51703. */
  51704. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  51705. this.source = source;
  51706. this.pointerX = pointerX;
  51707. this.pointerY = pointerY;
  51708. this.meshUnderPointer = meshUnderPointer;
  51709. this.sourceEvent = sourceEvent;
  51710. this.additionalData = additionalData;
  51711. }
  51712. /**
  51713. * Helper function to auto-create an ActionEvent from a source mesh.
  51714. * @param source The source mesh that triggered the event
  51715. * @param evt {Event} The original (browser) event
  51716. */
  51717. ActionEvent.CreateNew = function (source, evt, additionalData) {
  51718. var scene = source.getScene();
  51719. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51720. };
  51721. /**
  51722. * Helper function to auto-create an ActionEvent from a source mesh.
  51723. * @param source The source sprite that triggered the event
  51724. * @param scene Scene associated with the sprite
  51725. * @param evt {Event} The original (browser) event
  51726. */
  51727. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  51728. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51729. };
  51730. /**
  51731. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  51732. * @param scene the scene where the event occurred
  51733. * @param evt {Event} The original (browser) event
  51734. */
  51735. ActionEvent.CreateNewFromScene = function (scene, evt) {
  51736. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  51737. };
  51738. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  51739. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  51740. };
  51741. return ActionEvent;
  51742. }());
  51743. BABYLON.ActionEvent = ActionEvent;
  51744. /**
  51745. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  51746. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  51747. */
  51748. var ActionManager = /** @class */ (function () {
  51749. function ActionManager(scene) {
  51750. // Members
  51751. this.actions = new Array();
  51752. this.hoverCursor = '';
  51753. this._scene = scene;
  51754. scene._actionManagers.push(this);
  51755. }
  51756. Object.defineProperty(ActionManager, "NothingTrigger", {
  51757. get: function () {
  51758. return ActionManager._NothingTrigger;
  51759. },
  51760. enumerable: true,
  51761. configurable: true
  51762. });
  51763. Object.defineProperty(ActionManager, "OnPickTrigger", {
  51764. get: function () {
  51765. return ActionManager._OnPickTrigger;
  51766. },
  51767. enumerable: true,
  51768. configurable: true
  51769. });
  51770. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  51771. get: function () {
  51772. return ActionManager._OnLeftPickTrigger;
  51773. },
  51774. enumerable: true,
  51775. configurable: true
  51776. });
  51777. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  51778. get: function () {
  51779. return ActionManager._OnRightPickTrigger;
  51780. },
  51781. enumerable: true,
  51782. configurable: true
  51783. });
  51784. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  51785. get: function () {
  51786. return ActionManager._OnCenterPickTrigger;
  51787. },
  51788. enumerable: true,
  51789. configurable: true
  51790. });
  51791. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  51792. get: function () {
  51793. return ActionManager._OnPickDownTrigger;
  51794. },
  51795. enumerable: true,
  51796. configurable: true
  51797. });
  51798. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  51799. get: function () {
  51800. return ActionManager._OnDoublePickTrigger;
  51801. },
  51802. enumerable: true,
  51803. configurable: true
  51804. });
  51805. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  51806. get: function () {
  51807. return ActionManager._OnPickUpTrigger;
  51808. },
  51809. enumerable: true,
  51810. configurable: true
  51811. });
  51812. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  51813. /// This trigger will only be raised if you also declared a OnPickDown
  51814. get: function () {
  51815. return ActionManager._OnPickOutTrigger;
  51816. },
  51817. enumerable: true,
  51818. configurable: true
  51819. });
  51820. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  51821. get: function () {
  51822. return ActionManager._OnLongPressTrigger;
  51823. },
  51824. enumerable: true,
  51825. configurable: true
  51826. });
  51827. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  51828. get: function () {
  51829. return ActionManager._OnPointerOverTrigger;
  51830. },
  51831. enumerable: true,
  51832. configurable: true
  51833. });
  51834. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  51835. get: function () {
  51836. return ActionManager._OnPointerOutTrigger;
  51837. },
  51838. enumerable: true,
  51839. configurable: true
  51840. });
  51841. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  51842. get: function () {
  51843. return ActionManager._OnEveryFrameTrigger;
  51844. },
  51845. enumerable: true,
  51846. configurable: true
  51847. });
  51848. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  51849. get: function () {
  51850. return ActionManager._OnIntersectionEnterTrigger;
  51851. },
  51852. enumerable: true,
  51853. configurable: true
  51854. });
  51855. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  51856. get: function () {
  51857. return ActionManager._OnIntersectionExitTrigger;
  51858. },
  51859. enumerable: true,
  51860. configurable: true
  51861. });
  51862. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  51863. get: function () {
  51864. return ActionManager._OnKeyDownTrigger;
  51865. },
  51866. enumerable: true,
  51867. configurable: true
  51868. });
  51869. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  51870. get: function () {
  51871. return ActionManager._OnKeyUpTrigger;
  51872. },
  51873. enumerable: true,
  51874. configurable: true
  51875. });
  51876. // Methods
  51877. ActionManager.prototype.dispose = function () {
  51878. var index = this._scene._actionManagers.indexOf(this);
  51879. for (var i = 0; i < this.actions.length; i++) {
  51880. var action = this.actions[i];
  51881. ActionManager.Triggers[action.trigger]--;
  51882. if (ActionManager.Triggers[action.trigger] === 0) {
  51883. delete ActionManager.Triggers[action.trigger];
  51884. }
  51885. }
  51886. if (index > -1) {
  51887. this._scene._actionManagers.splice(index, 1);
  51888. }
  51889. };
  51890. ActionManager.prototype.getScene = function () {
  51891. return this._scene;
  51892. };
  51893. /**
  51894. * Does this action manager handles actions of any of the given triggers
  51895. * @param {number[]} triggers - the triggers to be tested
  51896. * @return {boolean} whether one (or more) of the triggers is handeled
  51897. */
  51898. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  51899. for (var index = 0; index < this.actions.length; index++) {
  51900. var action = this.actions[index];
  51901. if (triggers.indexOf(action.trigger) > -1) {
  51902. return true;
  51903. }
  51904. }
  51905. return false;
  51906. };
  51907. /**
  51908. * Does this action manager handles actions of a given trigger
  51909. * @param trigger defines the trigger to be tested
  51910. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  51911. * @return whether the trigger is handled
  51912. */
  51913. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  51914. for (var index = 0; index < this.actions.length; index++) {
  51915. var action = this.actions[index];
  51916. if (action.trigger === trigger) {
  51917. if (parameterPredicate) {
  51918. if (parameterPredicate(action.getTriggerParameter())) {
  51919. return true;
  51920. }
  51921. }
  51922. else {
  51923. return true;
  51924. }
  51925. }
  51926. }
  51927. return false;
  51928. };
  51929. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  51930. /**
  51931. * Does this action manager has pointer triggers
  51932. * @return {boolean} whether or not it has pointer triggers
  51933. */
  51934. get: function () {
  51935. for (var index = 0; index < this.actions.length; index++) {
  51936. var action = this.actions[index];
  51937. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  51938. return true;
  51939. }
  51940. }
  51941. return false;
  51942. },
  51943. enumerable: true,
  51944. configurable: true
  51945. });
  51946. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  51947. /**
  51948. * Does this action manager has pick triggers
  51949. * @return {boolean} whether or not it has pick triggers
  51950. */
  51951. get: function () {
  51952. for (var index = 0; index < this.actions.length; index++) {
  51953. var action = this.actions[index];
  51954. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  51955. return true;
  51956. }
  51957. }
  51958. return false;
  51959. },
  51960. enumerable: true,
  51961. configurable: true
  51962. });
  51963. Object.defineProperty(ActionManager, "HasTriggers", {
  51964. /**
  51965. * Does exist one action manager with at least one trigger
  51966. * @return {boolean} whether or not it exists one action manager with one trigger
  51967. **/
  51968. get: function () {
  51969. for (var t in ActionManager.Triggers) {
  51970. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51971. return true;
  51972. }
  51973. }
  51974. return false;
  51975. },
  51976. enumerable: true,
  51977. configurable: true
  51978. });
  51979. Object.defineProperty(ActionManager, "HasPickTriggers", {
  51980. /**
  51981. * Does exist one action manager with at least one pick trigger
  51982. * @return {boolean} whether or not it exists one action manager with one pick trigger
  51983. **/
  51984. get: function () {
  51985. for (var t in ActionManager.Triggers) {
  51986. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51987. var t_int = parseInt(t);
  51988. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  51989. return true;
  51990. }
  51991. }
  51992. }
  51993. return false;
  51994. },
  51995. enumerable: true,
  51996. configurable: true
  51997. });
  51998. /**
  51999. * Does exist one action manager that handles actions of a given trigger
  52000. * @param {number} trigger - the trigger to be tested
  52001. * @return {boolean} whether the trigger is handeled by at least one action manager
  52002. **/
  52003. ActionManager.HasSpecificTrigger = function (trigger) {
  52004. for (var t in ActionManager.Triggers) {
  52005. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52006. var t_int = parseInt(t);
  52007. if (t_int === trigger) {
  52008. return true;
  52009. }
  52010. }
  52011. }
  52012. return false;
  52013. };
  52014. /**
  52015. * Registers an action to this action manager
  52016. * @param {BABYLON.Action} action - the action to be registered
  52017. * @return {BABYLON.Action} the action amended (prepared) after registration
  52018. */
  52019. ActionManager.prototype.registerAction = function (action) {
  52020. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52021. if (this.getScene().actionManager !== this) {
  52022. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52023. return null;
  52024. }
  52025. }
  52026. this.actions.push(action);
  52027. if (ActionManager.Triggers[action.trigger]) {
  52028. ActionManager.Triggers[action.trigger]++;
  52029. }
  52030. else {
  52031. ActionManager.Triggers[action.trigger] = 1;
  52032. }
  52033. action._actionManager = this;
  52034. action._prepare();
  52035. return action;
  52036. };
  52037. /**
  52038. * Unregisters an action to this action manager
  52039. * @param action The action to be unregistered
  52040. * @return whether the action has been unregistered
  52041. */
  52042. ActionManager.prototype.unregisterAction = function (action) {
  52043. var index = this.actions.indexOf(action);
  52044. if (index !== -1) {
  52045. this.actions.splice(index, 1);
  52046. ActionManager.Triggers[action.trigger] -= 1;
  52047. if (ActionManager.Triggers[action.trigger] === 0) {
  52048. delete ActionManager.Triggers[action.trigger];
  52049. }
  52050. delete action._actionManager;
  52051. return true;
  52052. }
  52053. return false;
  52054. };
  52055. /**
  52056. * Process a specific trigger
  52057. * @param {number} trigger - the trigger to process
  52058. * @param evt {BABYLON.ActionEvent} the event details to be processed
  52059. */
  52060. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52061. for (var index = 0; index < this.actions.length; index++) {
  52062. var action = this.actions[index];
  52063. if (action.trigger === trigger) {
  52064. if (evt) {
  52065. if (trigger === ActionManager.OnKeyUpTrigger
  52066. || trigger === ActionManager.OnKeyDownTrigger) {
  52067. var parameter = action.getTriggerParameter();
  52068. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52069. if (!parameter.toLowerCase) {
  52070. continue;
  52071. }
  52072. var lowerCase = parameter.toLowerCase();
  52073. if (lowerCase !== evt.sourceEvent.key) {
  52074. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52075. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52076. if (actualkey !== lowerCase) {
  52077. continue;
  52078. }
  52079. }
  52080. }
  52081. }
  52082. }
  52083. action._executeCurrent(evt);
  52084. }
  52085. }
  52086. };
  52087. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52088. var properties = propertyPath.split(".");
  52089. for (var index = 0; index < properties.length - 1; index++) {
  52090. target = target[properties[index]];
  52091. }
  52092. return target;
  52093. };
  52094. ActionManager.prototype._getProperty = function (propertyPath) {
  52095. var properties = propertyPath.split(".");
  52096. return properties[properties.length - 1];
  52097. };
  52098. ActionManager.prototype.serialize = function (name) {
  52099. var root = {
  52100. children: new Array(),
  52101. name: name,
  52102. type: 3,
  52103. properties: new Array() // Empty for root but required
  52104. };
  52105. for (var i = 0; i < this.actions.length; i++) {
  52106. var triggerObject = {
  52107. type: 0,
  52108. children: new Array(),
  52109. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52110. properties: new Array()
  52111. };
  52112. var triggerOptions = this.actions[i].triggerOptions;
  52113. if (triggerOptions && typeof triggerOptions !== "number") {
  52114. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52115. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52116. }
  52117. else {
  52118. var parameter = {};
  52119. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52120. if (triggerOptions.parameter.mesh) {
  52121. parameter._meshId = triggerOptions.parameter.mesh.id;
  52122. }
  52123. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52124. }
  52125. }
  52126. // Serialize child action, recursively
  52127. this.actions[i].serialize(triggerObject);
  52128. // Add serialized trigger
  52129. root.children.push(triggerObject);
  52130. }
  52131. return root;
  52132. };
  52133. ActionManager.Parse = function (parsedActions, object, scene) {
  52134. var actionManager = new ActionManager(scene);
  52135. if (object === null)
  52136. scene.actionManager = actionManager;
  52137. else
  52138. object.actionManager = actionManager;
  52139. // instanciate a new object
  52140. var instanciate = function (name, params) {
  52141. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52142. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52143. newInstance.constructor.apply(newInstance, params);
  52144. return newInstance;
  52145. };
  52146. var parseParameter = function (name, value, target, propertyPath) {
  52147. if (propertyPath === null) {
  52148. // String, boolean or float
  52149. var floatValue = parseFloat(value);
  52150. if (value === "true" || value === "false")
  52151. return value === "true";
  52152. else
  52153. return isNaN(floatValue) ? value : floatValue;
  52154. }
  52155. var effectiveTarget = propertyPath.split(".");
  52156. var values = value.split(",");
  52157. // Get effective Target
  52158. for (var i = 0; i < effectiveTarget.length; i++) {
  52159. target = target[effectiveTarget[i]];
  52160. }
  52161. // Return appropriate value with its type
  52162. if (typeof (target) === "boolean")
  52163. return values[0] === "true";
  52164. if (typeof (target) === "string")
  52165. return values[0];
  52166. // Parameters with multiple values such as Vector3 etc.
  52167. var split = new Array();
  52168. for (var i = 0; i < values.length; i++)
  52169. split.push(parseFloat(values[i]));
  52170. if (target instanceof BABYLON.Vector3)
  52171. return BABYLON.Vector3.FromArray(split);
  52172. if (target instanceof BABYLON.Vector4)
  52173. return BABYLON.Vector4.FromArray(split);
  52174. if (target instanceof BABYLON.Color3)
  52175. return BABYLON.Color3.FromArray(split);
  52176. if (target instanceof BABYLON.Color4)
  52177. return BABYLON.Color4.FromArray(split);
  52178. return parseFloat(values[0]);
  52179. };
  52180. // traverse graph per trigger
  52181. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52182. if (combineArray === void 0) { combineArray = null; }
  52183. if (parsedAction.detached)
  52184. return;
  52185. var parameters = new Array();
  52186. var target = null;
  52187. var propertyPath = null;
  52188. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52189. // Parameters
  52190. if (parsedAction.type === 2)
  52191. parameters.push(actionManager);
  52192. else
  52193. parameters.push(trigger);
  52194. if (combine) {
  52195. var actions = new Array();
  52196. for (var j = 0; j < parsedAction.combine.length; j++) {
  52197. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52198. }
  52199. parameters.push(actions);
  52200. }
  52201. else {
  52202. for (var i = 0; i < parsedAction.properties.length; i++) {
  52203. var value = parsedAction.properties[i].value;
  52204. var name = parsedAction.properties[i].name;
  52205. var targetType = parsedAction.properties[i].targetType;
  52206. if (name === "target")
  52207. if (targetType !== null && targetType === "SceneProperties")
  52208. value = target = scene;
  52209. else
  52210. value = target = scene.getNodeByName(value);
  52211. else if (name === "parent")
  52212. value = scene.getNodeByName(value);
  52213. else if (name === "sound")
  52214. value = scene.getSoundByName(value);
  52215. else if (name !== "propertyPath") {
  52216. if (parsedAction.type === 2 && name === "operator")
  52217. value = BABYLON.ValueCondition[value];
  52218. else
  52219. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52220. }
  52221. else {
  52222. propertyPath = value;
  52223. }
  52224. parameters.push(value);
  52225. }
  52226. }
  52227. if (combineArray === null) {
  52228. parameters.push(condition);
  52229. }
  52230. else {
  52231. parameters.push(null);
  52232. }
  52233. // If interpolate value action
  52234. if (parsedAction.name === "InterpolateValueAction") {
  52235. var param = parameters[parameters.length - 2];
  52236. parameters[parameters.length - 1] = param;
  52237. parameters[parameters.length - 2] = condition;
  52238. }
  52239. // Action or condition(s) and not CombineAction
  52240. var newAction = instanciate(parsedAction.name, parameters);
  52241. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52242. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52243. if (action)
  52244. action.then(nothing);
  52245. else
  52246. actionManager.registerAction(nothing);
  52247. action = nothing;
  52248. }
  52249. if (combineArray === null) {
  52250. if (newAction instanceof BABYLON.Condition) {
  52251. condition = newAction;
  52252. newAction = action;
  52253. }
  52254. else {
  52255. condition = null;
  52256. if (action)
  52257. action.then(newAction);
  52258. else
  52259. actionManager.registerAction(newAction);
  52260. }
  52261. }
  52262. else {
  52263. combineArray.push(newAction);
  52264. }
  52265. for (var i = 0; i < parsedAction.children.length; i++)
  52266. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52267. };
  52268. // triggers
  52269. for (var i = 0; i < parsedActions.children.length; i++) {
  52270. var triggerParams;
  52271. var trigger = parsedActions.children[i];
  52272. if (trigger.properties.length > 0) {
  52273. var param = trigger.properties[0].value;
  52274. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52275. if (value._meshId) {
  52276. value.mesh = scene.getMeshByID(value._meshId);
  52277. }
  52278. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52279. }
  52280. else
  52281. triggerParams = ActionManager[trigger.name];
  52282. for (var j = 0; j < trigger.children.length; j++) {
  52283. if (!trigger.detached)
  52284. traverse(trigger.children[j], triggerParams, null, null);
  52285. }
  52286. }
  52287. };
  52288. ActionManager.GetTriggerName = function (trigger) {
  52289. switch (trigger) {
  52290. case 0: return "NothingTrigger";
  52291. case 1: return "OnPickTrigger";
  52292. case 2: return "OnLeftPickTrigger";
  52293. case 3: return "OnRightPickTrigger";
  52294. case 4: return "OnCenterPickTrigger";
  52295. case 5: return "OnPickDownTrigger";
  52296. case 6: return "OnPickUpTrigger";
  52297. case 7: return "OnLongPressTrigger";
  52298. case 8: return "OnPointerOverTrigger";
  52299. case 9: return "OnPointerOutTrigger";
  52300. case 10: return "OnEveryFrameTrigger";
  52301. case 11: return "OnIntersectionEnterTrigger";
  52302. case 12: return "OnIntersectionExitTrigger";
  52303. case 13: return "OnKeyDownTrigger";
  52304. case 14: return "OnKeyUpTrigger";
  52305. case 15: return "OnPickOutTrigger";
  52306. default: return "";
  52307. }
  52308. };
  52309. // Statics
  52310. ActionManager._NothingTrigger = 0;
  52311. ActionManager._OnPickTrigger = 1;
  52312. ActionManager._OnLeftPickTrigger = 2;
  52313. ActionManager._OnRightPickTrigger = 3;
  52314. ActionManager._OnCenterPickTrigger = 4;
  52315. ActionManager._OnPickDownTrigger = 5;
  52316. ActionManager._OnDoublePickTrigger = 6;
  52317. ActionManager._OnPickUpTrigger = 7;
  52318. ActionManager._OnLongPressTrigger = 8;
  52319. ActionManager._OnPointerOverTrigger = 9;
  52320. ActionManager._OnPointerOutTrigger = 10;
  52321. ActionManager._OnEveryFrameTrigger = 11;
  52322. ActionManager._OnIntersectionEnterTrigger = 12;
  52323. ActionManager._OnIntersectionExitTrigger = 13;
  52324. ActionManager._OnKeyDownTrigger = 14;
  52325. ActionManager._OnKeyUpTrigger = 15;
  52326. ActionManager._OnPickOutTrigger = 16;
  52327. ActionManager.Triggers = {};
  52328. return ActionManager;
  52329. }());
  52330. BABYLON.ActionManager = ActionManager;
  52331. })(BABYLON || (BABYLON = {}));
  52332. //# sourceMappingURL=babylon.actionManager.js.map
  52333. "use strict";
  52334. var BABYLON;
  52335. (function (BABYLON) {
  52336. var InterpolateValueAction = /** @class */ (function (_super) {
  52337. __extends(InterpolateValueAction, _super);
  52338. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52339. if (duration === void 0) { duration = 1000; }
  52340. var _this = _super.call(this, triggerOptions, condition) || this;
  52341. _this.propertyPath = propertyPath;
  52342. _this.value = value;
  52343. _this.duration = duration;
  52344. _this.stopOtherAnimations = stopOtherAnimations;
  52345. _this.onInterpolationDone = onInterpolationDone;
  52346. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52347. _this._target = _this._effectiveTarget = target;
  52348. return _this;
  52349. }
  52350. InterpolateValueAction.prototype._prepare = function () {
  52351. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52352. this._property = this._getProperty(this.propertyPath);
  52353. };
  52354. InterpolateValueAction.prototype.execute = function () {
  52355. var _this = this;
  52356. var scene = this._actionManager.getScene();
  52357. var keys = [
  52358. {
  52359. frame: 0,
  52360. value: this._effectiveTarget[this._property]
  52361. }, {
  52362. frame: 100,
  52363. value: this.value
  52364. }
  52365. ];
  52366. var dataType;
  52367. if (typeof this.value === "number") {
  52368. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52369. }
  52370. else if (this.value instanceof BABYLON.Color3) {
  52371. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52372. }
  52373. else if (this.value instanceof BABYLON.Vector3) {
  52374. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52375. }
  52376. else if (this.value instanceof BABYLON.Matrix) {
  52377. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52378. }
  52379. else if (this.value instanceof BABYLON.Quaternion) {
  52380. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52381. }
  52382. else {
  52383. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52384. return;
  52385. }
  52386. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52387. animation.setKeys(keys);
  52388. if (this.stopOtherAnimations) {
  52389. scene.stopAnimation(this._effectiveTarget);
  52390. }
  52391. var wrapper = function () {
  52392. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52393. if (_this.onInterpolationDone) {
  52394. _this.onInterpolationDone();
  52395. }
  52396. };
  52397. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52398. };
  52399. InterpolateValueAction.prototype.serialize = function (parent) {
  52400. return _super.prototype._serialize.call(this, {
  52401. name: "InterpolateValueAction",
  52402. properties: [
  52403. BABYLON.Action._GetTargetProperty(this._target),
  52404. { name: "propertyPath", value: this.propertyPath },
  52405. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52406. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52407. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52408. ]
  52409. }, parent);
  52410. };
  52411. return InterpolateValueAction;
  52412. }(BABYLON.Action));
  52413. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52414. })(BABYLON || (BABYLON = {}));
  52415. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52416. "use strict";
  52417. var BABYLON;
  52418. (function (BABYLON) {
  52419. var SwitchBooleanAction = /** @class */ (function (_super) {
  52420. __extends(SwitchBooleanAction, _super);
  52421. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52422. var _this = _super.call(this, triggerOptions, condition) || this;
  52423. _this.propertyPath = propertyPath;
  52424. _this._target = _this._effectiveTarget = target;
  52425. return _this;
  52426. }
  52427. SwitchBooleanAction.prototype._prepare = function () {
  52428. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52429. this._property = this._getProperty(this.propertyPath);
  52430. };
  52431. SwitchBooleanAction.prototype.execute = function () {
  52432. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52433. };
  52434. SwitchBooleanAction.prototype.serialize = function (parent) {
  52435. return _super.prototype._serialize.call(this, {
  52436. name: "SwitchBooleanAction",
  52437. properties: [
  52438. BABYLON.Action._GetTargetProperty(this._target),
  52439. { name: "propertyPath", value: this.propertyPath }
  52440. ]
  52441. }, parent);
  52442. };
  52443. return SwitchBooleanAction;
  52444. }(BABYLON.Action));
  52445. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52446. var SetStateAction = /** @class */ (function (_super) {
  52447. __extends(SetStateAction, _super);
  52448. function SetStateAction(triggerOptions, target, value, condition) {
  52449. var _this = _super.call(this, triggerOptions, condition) || this;
  52450. _this.value = value;
  52451. _this._target = target;
  52452. return _this;
  52453. }
  52454. SetStateAction.prototype.execute = function () {
  52455. this._target.state = this.value;
  52456. };
  52457. SetStateAction.prototype.serialize = function (parent) {
  52458. return _super.prototype._serialize.call(this, {
  52459. name: "SetStateAction",
  52460. properties: [
  52461. BABYLON.Action._GetTargetProperty(this._target),
  52462. { name: "value", value: this.value }
  52463. ]
  52464. }, parent);
  52465. };
  52466. return SetStateAction;
  52467. }(BABYLON.Action));
  52468. BABYLON.SetStateAction = SetStateAction;
  52469. var SetValueAction = /** @class */ (function (_super) {
  52470. __extends(SetValueAction, _super);
  52471. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52472. var _this = _super.call(this, triggerOptions, condition) || this;
  52473. _this.propertyPath = propertyPath;
  52474. _this.value = value;
  52475. _this._target = _this._effectiveTarget = target;
  52476. return _this;
  52477. }
  52478. SetValueAction.prototype._prepare = function () {
  52479. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52480. this._property = this._getProperty(this.propertyPath);
  52481. };
  52482. SetValueAction.prototype.execute = function () {
  52483. this._effectiveTarget[this._property] = this.value;
  52484. if (this._target.markAsDirty) {
  52485. this._target.markAsDirty(this._property);
  52486. }
  52487. };
  52488. SetValueAction.prototype.serialize = function (parent) {
  52489. return _super.prototype._serialize.call(this, {
  52490. name: "SetValueAction",
  52491. properties: [
  52492. BABYLON.Action._GetTargetProperty(this._target),
  52493. { name: "propertyPath", value: this.propertyPath },
  52494. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52495. ]
  52496. }, parent);
  52497. };
  52498. return SetValueAction;
  52499. }(BABYLON.Action));
  52500. BABYLON.SetValueAction = SetValueAction;
  52501. var IncrementValueAction = /** @class */ (function (_super) {
  52502. __extends(IncrementValueAction, _super);
  52503. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52504. var _this = _super.call(this, triggerOptions, condition) || this;
  52505. _this.propertyPath = propertyPath;
  52506. _this.value = value;
  52507. _this._target = _this._effectiveTarget = target;
  52508. return _this;
  52509. }
  52510. IncrementValueAction.prototype._prepare = function () {
  52511. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52512. this._property = this._getProperty(this.propertyPath);
  52513. if (typeof this._effectiveTarget[this._property] !== "number") {
  52514. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  52515. }
  52516. };
  52517. IncrementValueAction.prototype.execute = function () {
  52518. this._effectiveTarget[this._property] += this.value;
  52519. if (this._target.markAsDirty) {
  52520. this._target.markAsDirty(this._property);
  52521. }
  52522. };
  52523. IncrementValueAction.prototype.serialize = function (parent) {
  52524. return _super.prototype._serialize.call(this, {
  52525. name: "IncrementValueAction",
  52526. properties: [
  52527. BABYLON.Action._GetTargetProperty(this._target),
  52528. { name: "propertyPath", value: this.propertyPath },
  52529. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52530. ]
  52531. }, parent);
  52532. };
  52533. return IncrementValueAction;
  52534. }(BABYLON.Action));
  52535. BABYLON.IncrementValueAction = IncrementValueAction;
  52536. var PlayAnimationAction = /** @class */ (function (_super) {
  52537. __extends(PlayAnimationAction, _super);
  52538. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  52539. var _this = _super.call(this, triggerOptions, condition) || this;
  52540. _this.from = from;
  52541. _this.to = to;
  52542. _this.loop = loop;
  52543. _this._target = target;
  52544. return _this;
  52545. }
  52546. PlayAnimationAction.prototype._prepare = function () {
  52547. };
  52548. PlayAnimationAction.prototype.execute = function () {
  52549. var scene = this._actionManager.getScene();
  52550. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  52551. };
  52552. PlayAnimationAction.prototype.serialize = function (parent) {
  52553. return _super.prototype._serialize.call(this, {
  52554. name: "PlayAnimationAction",
  52555. properties: [
  52556. BABYLON.Action._GetTargetProperty(this._target),
  52557. { name: "from", value: String(this.from) },
  52558. { name: "to", value: String(this.to) },
  52559. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  52560. ]
  52561. }, parent);
  52562. };
  52563. return PlayAnimationAction;
  52564. }(BABYLON.Action));
  52565. BABYLON.PlayAnimationAction = PlayAnimationAction;
  52566. var StopAnimationAction = /** @class */ (function (_super) {
  52567. __extends(StopAnimationAction, _super);
  52568. function StopAnimationAction(triggerOptions, target, condition) {
  52569. var _this = _super.call(this, triggerOptions, condition) || this;
  52570. _this._target = target;
  52571. return _this;
  52572. }
  52573. StopAnimationAction.prototype._prepare = function () {
  52574. };
  52575. StopAnimationAction.prototype.execute = function () {
  52576. var scene = this._actionManager.getScene();
  52577. scene.stopAnimation(this._target);
  52578. };
  52579. StopAnimationAction.prototype.serialize = function (parent) {
  52580. return _super.prototype._serialize.call(this, {
  52581. name: "StopAnimationAction",
  52582. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  52583. }, parent);
  52584. };
  52585. return StopAnimationAction;
  52586. }(BABYLON.Action));
  52587. BABYLON.StopAnimationAction = StopAnimationAction;
  52588. var DoNothingAction = /** @class */ (function (_super) {
  52589. __extends(DoNothingAction, _super);
  52590. function DoNothingAction(triggerOptions, condition) {
  52591. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  52592. return _super.call(this, triggerOptions, condition) || this;
  52593. }
  52594. DoNothingAction.prototype.execute = function () {
  52595. };
  52596. DoNothingAction.prototype.serialize = function (parent) {
  52597. return _super.prototype._serialize.call(this, {
  52598. name: "DoNothingAction",
  52599. properties: []
  52600. }, parent);
  52601. };
  52602. return DoNothingAction;
  52603. }(BABYLON.Action));
  52604. BABYLON.DoNothingAction = DoNothingAction;
  52605. var CombineAction = /** @class */ (function (_super) {
  52606. __extends(CombineAction, _super);
  52607. function CombineAction(triggerOptions, children, condition) {
  52608. var _this = _super.call(this, triggerOptions, condition) || this;
  52609. _this.children = children;
  52610. return _this;
  52611. }
  52612. CombineAction.prototype._prepare = function () {
  52613. for (var index = 0; index < this.children.length; index++) {
  52614. this.children[index]._actionManager = this._actionManager;
  52615. this.children[index]._prepare();
  52616. }
  52617. };
  52618. CombineAction.prototype.execute = function (evt) {
  52619. for (var index = 0; index < this.children.length; index++) {
  52620. this.children[index].execute(evt);
  52621. }
  52622. };
  52623. CombineAction.prototype.serialize = function (parent) {
  52624. var serializationObject = _super.prototype._serialize.call(this, {
  52625. name: "CombineAction",
  52626. properties: [],
  52627. combine: []
  52628. }, parent);
  52629. for (var i = 0; i < this.children.length; i++) {
  52630. serializationObject.combine.push(this.children[i].serialize(null));
  52631. }
  52632. return serializationObject;
  52633. };
  52634. return CombineAction;
  52635. }(BABYLON.Action));
  52636. BABYLON.CombineAction = CombineAction;
  52637. var ExecuteCodeAction = /** @class */ (function (_super) {
  52638. __extends(ExecuteCodeAction, _super);
  52639. function ExecuteCodeAction(triggerOptions, func, condition) {
  52640. var _this = _super.call(this, triggerOptions, condition) || this;
  52641. _this.func = func;
  52642. return _this;
  52643. }
  52644. ExecuteCodeAction.prototype.execute = function (evt) {
  52645. this.func(evt);
  52646. };
  52647. return ExecuteCodeAction;
  52648. }(BABYLON.Action));
  52649. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  52650. var SetParentAction = /** @class */ (function (_super) {
  52651. __extends(SetParentAction, _super);
  52652. function SetParentAction(triggerOptions, target, parent, condition) {
  52653. var _this = _super.call(this, triggerOptions, condition) || this;
  52654. _this._target = target;
  52655. _this._parent = parent;
  52656. return _this;
  52657. }
  52658. SetParentAction.prototype._prepare = function () {
  52659. };
  52660. SetParentAction.prototype.execute = function () {
  52661. if (this._target.parent === this._parent) {
  52662. return;
  52663. }
  52664. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  52665. invertParentWorldMatrix.invert();
  52666. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  52667. this._target.parent = this._parent;
  52668. };
  52669. SetParentAction.prototype.serialize = function (parent) {
  52670. return _super.prototype._serialize.call(this, {
  52671. name: "SetParentAction",
  52672. properties: [
  52673. BABYLON.Action._GetTargetProperty(this._target),
  52674. BABYLON.Action._GetTargetProperty(this._parent),
  52675. ]
  52676. }, parent);
  52677. };
  52678. return SetParentAction;
  52679. }(BABYLON.Action));
  52680. BABYLON.SetParentAction = SetParentAction;
  52681. var PlaySoundAction = /** @class */ (function (_super) {
  52682. __extends(PlaySoundAction, _super);
  52683. function PlaySoundAction(triggerOptions, sound, condition) {
  52684. var _this = _super.call(this, triggerOptions, condition) || this;
  52685. _this._sound = sound;
  52686. return _this;
  52687. }
  52688. PlaySoundAction.prototype._prepare = function () {
  52689. };
  52690. PlaySoundAction.prototype.execute = function () {
  52691. if (this._sound !== undefined)
  52692. this._sound.play();
  52693. };
  52694. PlaySoundAction.prototype.serialize = function (parent) {
  52695. return _super.prototype._serialize.call(this, {
  52696. name: "PlaySoundAction",
  52697. properties: [{ name: "sound", value: this._sound.name }]
  52698. }, parent);
  52699. };
  52700. return PlaySoundAction;
  52701. }(BABYLON.Action));
  52702. BABYLON.PlaySoundAction = PlaySoundAction;
  52703. var StopSoundAction = /** @class */ (function (_super) {
  52704. __extends(StopSoundAction, _super);
  52705. function StopSoundAction(triggerOptions, sound, condition) {
  52706. var _this = _super.call(this, triggerOptions, condition) || this;
  52707. _this._sound = sound;
  52708. return _this;
  52709. }
  52710. StopSoundAction.prototype._prepare = function () {
  52711. };
  52712. StopSoundAction.prototype.execute = function () {
  52713. if (this._sound !== undefined)
  52714. this._sound.stop();
  52715. };
  52716. StopSoundAction.prototype.serialize = function (parent) {
  52717. return _super.prototype._serialize.call(this, {
  52718. name: "StopSoundAction",
  52719. properties: [{ name: "sound", value: this._sound.name }]
  52720. }, parent);
  52721. };
  52722. return StopSoundAction;
  52723. }(BABYLON.Action));
  52724. BABYLON.StopSoundAction = StopSoundAction;
  52725. })(BABYLON || (BABYLON = {}));
  52726. //# sourceMappingURL=babylon.directActions.js.map
  52727. "use strict";
  52728. var BABYLON;
  52729. (function (BABYLON) {
  52730. var SpriteManager = /** @class */ (function () {
  52731. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  52732. if (epsilon === void 0) { epsilon = 0.01; }
  52733. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52734. this.name = name;
  52735. this.sprites = new Array();
  52736. this.renderingGroupId = 0;
  52737. this.layerMask = 0x0FFFFFFF;
  52738. this.fogEnabled = true;
  52739. this.isPickable = false;
  52740. /**
  52741. * An event triggered when the manager is disposed.
  52742. */
  52743. this.onDisposeObservable = new BABYLON.Observable();
  52744. this._vertexBuffers = {};
  52745. this._capacity = capacity;
  52746. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  52747. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52748. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52749. if (cellSize.width && cellSize.height) {
  52750. this.cellWidth = cellSize.width;
  52751. this.cellHeight = cellSize.height;
  52752. }
  52753. else if (cellSize !== undefined) {
  52754. this.cellWidth = cellSize;
  52755. this.cellHeight = cellSize;
  52756. }
  52757. else {
  52758. return;
  52759. }
  52760. this._epsilon = epsilon;
  52761. this._scene = scene;
  52762. this._scene.spriteManagers.push(this);
  52763. var indices = [];
  52764. var index = 0;
  52765. for (var count = 0; count < capacity; count++) {
  52766. indices.push(index);
  52767. indices.push(index + 1);
  52768. indices.push(index + 2);
  52769. indices.push(index);
  52770. indices.push(index + 2);
  52771. indices.push(index + 3);
  52772. index += 4;
  52773. }
  52774. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  52775. // VBO
  52776. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  52777. this._vertexData = new Float32Array(capacity * 16 * 4);
  52778. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  52779. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  52780. var options = this._buffer.createVertexBuffer("options", 4, 4);
  52781. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  52782. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  52783. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  52784. this._vertexBuffers["options"] = options;
  52785. this._vertexBuffers["cellInfo"] = cellInfo;
  52786. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  52787. // Effects
  52788. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  52789. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  52790. }
  52791. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  52792. set: function (callback) {
  52793. if (this._onDisposeObserver) {
  52794. this.onDisposeObservable.remove(this._onDisposeObserver);
  52795. }
  52796. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52797. },
  52798. enumerable: true,
  52799. configurable: true
  52800. });
  52801. Object.defineProperty(SpriteManager.prototype, "texture", {
  52802. get: function () {
  52803. return this._spriteTexture;
  52804. },
  52805. set: function (value) {
  52806. this._spriteTexture = value;
  52807. },
  52808. enumerable: true,
  52809. configurable: true
  52810. });
  52811. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  52812. var arrayOffset = index * 16;
  52813. if (offsetX === 0)
  52814. offsetX = this._epsilon;
  52815. else if (offsetX === 1)
  52816. offsetX = 1 - this._epsilon;
  52817. if (offsetY === 0)
  52818. offsetY = this._epsilon;
  52819. else if (offsetY === 1)
  52820. offsetY = 1 - this._epsilon;
  52821. this._vertexData[arrayOffset] = sprite.position.x;
  52822. this._vertexData[arrayOffset + 1] = sprite.position.y;
  52823. this._vertexData[arrayOffset + 2] = sprite.position.z;
  52824. this._vertexData[arrayOffset + 3] = sprite.angle;
  52825. this._vertexData[arrayOffset + 4] = sprite.width;
  52826. this._vertexData[arrayOffset + 5] = sprite.height;
  52827. this._vertexData[arrayOffset + 6] = offsetX;
  52828. this._vertexData[arrayOffset + 7] = offsetY;
  52829. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  52830. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  52831. var offset = (sprite.cellIndex / rowSize) >> 0;
  52832. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  52833. this._vertexData[arrayOffset + 11] = offset;
  52834. // Color
  52835. this._vertexData[arrayOffset + 12] = sprite.color.r;
  52836. this._vertexData[arrayOffset + 13] = sprite.color.g;
  52837. this._vertexData[arrayOffset + 14] = sprite.color.b;
  52838. this._vertexData[arrayOffset + 15] = sprite.color.a;
  52839. };
  52840. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  52841. var count = Math.min(this._capacity, this.sprites.length);
  52842. var min = BABYLON.Vector3.Zero();
  52843. var max = BABYLON.Vector3.Zero();
  52844. var distance = Number.MAX_VALUE;
  52845. var currentSprite = null;
  52846. var cameraSpacePosition = BABYLON.Vector3.Zero();
  52847. var cameraView = camera.getViewMatrix();
  52848. for (var index = 0; index < count; index++) {
  52849. var sprite = this.sprites[index];
  52850. if (!sprite) {
  52851. continue;
  52852. }
  52853. if (predicate) {
  52854. if (!predicate(sprite)) {
  52855. continue;
  52856. }
  52857. }
  52858. else if (!sprite.isPickable) {
  52859. continue;
  52860. }
  52861. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  52862. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  52863. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  52864. if (ray.intersectsBoxMinMax(min, max)) {
  52865. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  52866. if (distance > currentDistance) {
  52867. distance = currentDistance;
  52868. currentSprite = sprite;
  52869. if (fastCheck) {
  52870. break;
  52871. }
  52872. }
  52873. }
  52874. }
  52875. if (currentSprite) {
  52876. var result = new BABYLON.PickingInfo();
  52877. result.hit = true;
  52878. result.pickedSprite = currentSprite;
  52879. result.distance = distance;
  52880. return result;
  52881. }
  52882. return null;
  52883. };
  52884. SpriteManager.prototype.render = function () {
  52885. // Check
  52886. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  52887. return;
  52888. var engine = this._scene.getEngine();
  52889. var baseSize = this._spriteTexture.getBaseSize();
  52890. // Sprites
  52891. var deltaTime = engine.getDeltaTime();
  52892. var max = Math.min(this._capacity, this.sprites.length);
  52893. var rowSize = baseSize.width / this.cellWidth;
  52894. var offset = 0;
  52895. for (var index = 0; index < max; index++) {
  52896. var sprite = this.sprites[index];
  52897. if (!sprite) {
  52898. continue;
  52899. }
  52900. sprite._animate(deltaTime);
  52901. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  52902. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  52903. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  52904. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  52905. }
  52906. this._buffer.update(this._vertexData);
  52907. // Render
  52908. var effect = this._effectBase;
  52909. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  52910. effect = this._effectFog;
  52911. }
  52912. engine.enableEffect(effect);
  52913. var viewMatrix = this._scene.getViewMatrix();
  52914. effect.setTexture("diffuseSampler", this._spriteTexture);
  52915. effect.setMatrix("view", viewMatrix);
  52916. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52917. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  52918. // Fog
  52919. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  52920. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  52921. effect.setColor3("vFogColor", this._scene.fogColor);
  52922. }
  52923. // VBOs
  52924. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52925. // Draw order
  52926. engine.setDepthFunctionToLessOrEqual();
  52927. effect.setBool("alphaTest", true);
  52928. engine.setColorWrite(false);
  52929. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  52930. engine.setColorWrite(true);
  52931. effect.setBool("alphaTest", false);
  52932. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52933. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  52934. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52935. };
  52936. SpriteManager.prototype.dispose = function () {
  52937. if (this._buffer) {
  52938. this._buffer.dispose();
  52939. this._buffer = null;
  52940. }
  52941. if (this._indexBuffer) {
  52942. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52943. this._indexBuffer = null;
  52944. }
  52945. if (this._spriteTexture) {
  52946. this._spriteTexture.dispose();
  52947. this._spriteTexture = null;
  52948. }
  52949. // Remove from scene
  52950. var index = this._scene.spriteManagers.indexOf(this);
  52951. this._scene.spriteManagers.splice(index, 1);
  52952. // Callback
  52953. this.onDisposeObservable.notifyObservers(this);
  52954. this.onDisposeObservable.clear();
  52955. };
  52956. return SpriteManager;
  52957. }());
  52958. BABYLON.SpriteManager = SpriteManager;
  52959. })(BABYLON || (BABYLON = {}));
  52960. //# sourceMappingURL=babylon.spriteManager.js.map
  52961. "use strict";
  52962. var BABYLON;
  52963. (function (BABYLON) {
  52964. var Sprite = /** @class */ (function () {
  52965. function Sprite(name, manager) {
  52966. this.name = name;
  52967. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52968. this.width = 1.0;
  52969. this.height = 1.0;
  52970. this.angle = 0;
  52971. this.cellIndex = 0;
  52972. this.invertU = 0;
  52973. this.invertV = 0;
  52974. this.animations = new Array();
  52975. this.isPickable = false;
  52976. this._animationStarted = false;
  52977. this._loopAnimation = false;
  52978. this._fromIndex = 0;
  52979. this._toIndex = 0;
  52980. this._delay = 0;
  52981. this._direction = 1;
  52982. this._time = 0;
  52983. this._manager = manager;
  52984. this._manager.sprites.push(this);
  52985. this.position = BABYLON.Vector3.Zero();
  52986. }
  52987. Object.defineProperty(Sprite.prototype, "size", {
  52988. get: function () {
  52989. return this.width;
  52990. },
  52991. set: function (value) {
  52992. this.width = value;
  52993. this.height = value;
  52994. },
  52995. enumerable: true,
  52996. configurable: true
  52997. });
  52998. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  52999. this._fromIndex = from;
  53000. this._toIndex = to;
  53001. this._loopAnimation = loop;
  53002. this._delay = delay;
  53003. this._animationStarted = true;
  53004. this._direction = from < to ? 1 : -1;
  53005. this.cellIndex = from;
  53006. this._time = 0;
  53007. this._onAnimationEnd = onAnimationEnd;
  53008. };
  53009. Sprite.prototype.stopAnimation = function () {
  53010. this._animationStarted = false;
  53011. };
  53012. Sprite.prototype._animate = function (deltaTime) {
  53013. if (!this._animationStarted)
  53014. return;
  53015. this._time += deltaTime;
  53016. if (this._time > this._delay) {
  53017. this._time = this._time % this._delay;
  53018. this.cellIndex += this._direction;
  53019. if (this.cellIndex > this._toIndex) {
  53020. if (this._loopAnimation) {
  53021. this.cellIndex = this._fromIndex;
  53022. }
  53023. else {
  53024. this.cellIndex = this._toIndex;
  53025. this._animationStarted = false;
  53026. if (this._onAnimationEnd) {
  53027. this._onAnimationEnd();
  53028. }
  53029. if (this.disposeWhenFinishedAnimating) {
  53030. this.dispose();
  53031. }
  53032. }
  53033. }
  53034. }
  53035. };
  53036. Sprite.prototype.dispose = function () {
  53037. for (var i = 0; i < this._manager.sprites.length; i++) {
  53038. if (this._manager.sprites[i] == this) {
  53039. this._manager.sprites.splice(i, 1);
  53040. }
  53041. }
  53042. };
  53043. return Sprite;
  53044. }());
  53045. BABYLON.Sprite = Sprite;
  53046. })(BABYLON || (BABYLON = {}));
  53047. //# sourceMappingURL=babylon.sprite.js.map
  53048. "use strict";
  53049. var BABYLON;
  53050. (function (BABYLON) {
  53051. var IntersectionInfo = /** @class */ (function () {
  53052. function IntersectionInfo(bu, bv, distance) {
  53053. this.bu = bu;
  53054. this.bv = bv;
  53055. this.distance = distance;
  53056. this.faceId = 0;
  53057. this.subMeshId = 0;
  53058. }
  53059. return IntersectionInfo;
  53060. }());
  53061. BABYLON.IntersectionInfo = IntersectionInfo;
  53062. var PickingInfo = /** @class */ (function () {
  53063. function PickingInfo() {
  53064. this.hit = false;
  53065. this.distance = 0;
  53066. this.pickedPoint = null;
  53067. this.pickedMesh = null;
  53068. this.bu = 0;
  53069. this.bv = 0;
  53070. this.faceId = -1;
  53071. this.subMeshId = 0;
  53072. this.pickedSprite = null;
  53073. }
  53074. // Methods
  53075. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53076. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53077. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53078. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53079. return null;
  53080. }
  53081. var indices = this.pickedMesh.getIndices();
  53082. if (!indices) {
  53083. return null;
  53084. }
  53085. var result;
  53086. if (useVerticesNormals) {
  53087. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53088. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53089. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53090. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53091. normal0 = normal0.scale(this.bu);
  53092. normal1 = normal1.scale(this.bv);
  53093. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53094. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53095. }
  53096. else {
  53097. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53098. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53099. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53100. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53101. var p1p2 = vertex1.subtract(vertex2);
  53102. var p3p2 = vertex3.subtract(vertex2);
  53103. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53104. }
  53105. if (useWorldCoordinates) {
  53106. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53107. }
  53108. return BABYLON.Vector3.Normalize(result);
  53109. };
  53110. PickingInfo.prototype.getTextureCoordinates = function () {
  53111. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53112. return null;
  53113. }
  53114. var indices = this.pickedMesh.getIndices();
  53115. if (!indices) {
  53116. return null;
  53117. }
  53118. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53119. if (!uvs) {
  53120. return null;
  53121. }
  53122. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53123. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53124. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53125. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53126. uv1 = uv1.scale(this.bu);
  53127. uv2 = uv2.scale(this.bv);
  53128. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53129. };
  53130. return PickingInfo;
  53131. }());
  53132. BABYLON.PickingInfo = PickingInfo;
  53133. })(BABYLON || (BABYLON = {}));
  53134. //# sourceMappingURL=babylon.pickingInfo.js.map
  53135. "use strict";
  53136. var BABYLON;
  53137. (function (BABYLON) {
  53138. var Ray = /** @class */ (function () {
  53139. function Ray(origin, direction, length) {
  53140. if (length === void 0) { length = Number.MAX_VALUE; }
  53141. this.origin = origin;
  53142. this.direction = direction;
  53143. this.length = length;
  53144. }
  53145. // Methods
  53146. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53147. var d = 0.0;
  53148. var maxValue = Number.MAX_VALUE;
  53149. var inv;
  53150. var min;
  53151. var max;
  53152. var temp;
  53153. if (Math.abs(this.direction.x) < 0.0000001) {
  53154. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53155. return false;
  53156. }
  53157. }
  53158. else {
  53159. inv = 1.0 / this.direction.x;
  53160. min = (minimum.x - this.origin.x) * inv;
  53161. max = (maximum.x - this.origin.x) * inv;
  53162. if (max === -Infinity) {
  53163. max = Infinity;
  53164. }
  53165. if (min > max) {
  53166. temp = min;
  53167. min = max;
  53168. max = temp;
  53169. }
  53170. d = Math.max(min, d);
  53171. maxValue = Math.min(max, maxValue);
  53172. if (d > maxValue) {
  53173. return false;
  53174. }
  53175. }
  53176. if (Math.abs(this.direction.y) < 0.0000001) {
  53177. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53178. return false;
  53179. }
  53180. }
  53181. else {
  53182. inv = 1.0 / this.direction.y;
  53183. min = (minimum.y - this.origin.y) * inv;
  53184. max = (maximum.y - this.origin.y) * inv;
  53185. if (max === -Infinity) {
  53186. max = Infinity;
  53187. }
  53188. if (min > max) {
  53189. temp = min;
  53190. min = max;
  53191. max = temp;
  53192. }
  53193. d = Math.max(min, d);
  53194. maxValue = Math.min(max, maxValue);
  53195. if (d > maxValue) {
  53196. return false;
  53197. }
  53198. }
  53199. if (Math.abs(this.direction.z) < 0.0000001) {
  53200. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53201. return false;
  53202. }
  53203. }
  53204. else {
  53205. inv = 1.0 / this.direction.z;
  53206. min = (minimum.z - this.origin.z) * inv;
  53207. max = (maximum.z - this.origin.z) * inv;
  53208. if (max === -Infinity) {
  53209. max = Infinity;
  53210. }
  53211. if (min > max) {
  53212. temp = min;
  53213. min = max;
  53214. max = temp;
  53215. }
  53216. d = Math.max(min, d);
  53217. maxValue = Math.min(max, maxValue);
  53218. if (d > maxValue) {
  53219. return false;
  53220. }
  53221. }
  53222. return true;
  53223. };
  53224. Ray.prototype.intersectsBox = function (box) {
  53225. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53226. };
  53227. Ray.prototype.intersectsSphere = function (sphere) {
  53228. var x = sphere.center.x - this.origin.x;
  53229. var y = sphere.center.y - this.origin.y;
  53230. var z = sphere.center.z - this.origin.z;
  53231. var pyth = (x * x) + (y * y) + (z * z);
  53232. var rr = sphere.radius * sphere.radius;
  53233. if (pyth <= rr) {
  53234. return true;
  53235. }
  53236. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53237. if (dot < 0.0) {
  53238. return false;
  53239. }
  53240. var temp = pyth - (dot * dot);
  53241. return temp <= rr;
  53242. };
  53243. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53244. if (!this._edge1) {
  53245. this._edge1 = BABYLON.Vector3.Zero();
  53246. this._edge2 = BABYLON.Vector3.Zero();
  53247. this._pvec = BABYLON.Vector3.Zero();
  53248. this._tvec = BABYLON.Vector3.Zero();
  53249. this._qvec = BABYLON.Vector3.Zero();
  53250. }
  53251. vertex1.subtractToRef(vertex0, this._edge1);
  53252. vertex2.subtractToRef(vertex0, this._edge2);
  53253. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53254. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53255. if (det === 0) {
  53256. return null;
  53257. }
  53258. var invdet = 1 / det;
  53259. this.origin.subtractToRef(vertex0, this._tvec);
  53260. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53261. if (bu < 0 || bu > 1.0) {
  53262. return null;
  53263. }
  53264. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53265. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53266. if (bv < 0 || bu + bv > 1.0) {
  53267. return null;
  53268. }
  53269. //check if the distance is longer than the predefined length.
  53270. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53271. if (distance > this.length) {
  53272. return null;
  53273. }
  53274. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53275. };
  53276. Ray.prototype.intersectsPlane = function (plane) {
  53277. var distance;
  53278. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53279. if (Math.abs(result1) < 9.99999997475243E-07) {
  53280. return null;
  53281. }
  53282. else {
  53283. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53284. distance = (-plane.d - result2) / result1;
  53285. if (distance < 0.0) {
  53286. if (distance < -9.99999997475243E-07) {
  53287. return null;
  53288. }
  53289. else {
  53290. return 0;
  53291. }
  53292. }
  53293. return distance;
  53294. }
  53295. };
  53296. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53297. var tm = BABYLON.Tmp.Matrix[0];
  53298. mesh.getWorldMatrix().invertToRef(tm);
  53299. if (this._tmpRay) {
  53300. Ray.TransformToRef(this, tm, this._tmpRay);
  53301. }
  53302. else {
  53303. this._tmpRay = Ray.Transform(this, tm);
  53304. }
  53305. return mesh.intersects(this._tmpRay, fastCheck);
  53306. };
  53307. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53308. if (results) {
  53309. results.length = 0;
  53310. }
  53311. else {
  53312. results = [];
  53313. }
  53314. for (var i = 0; i < meshes.length; i++) {
  53315. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53316. if (pickInfo.hit) {
  53317. results.push(pickInfo);
  53318. }
  53319. }
  53320. results.sort(this._comparePickingInfo);
  53321. return results;
  53322. };
  53323. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53324. if (pickingInfoA.distance < pickingInfoB.distance) {
  53325. return -1;
  53326. }
  53327. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53328. return 1;
  53329. }
  53330. else {
  53331. return 0;
  53332. }
  53333. };
  53334. /**
  53335. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53336. * @param sega the first point of the segment to test the intersection against
  53337. * @param segb the second point of the segment to test the intersection against
  53338. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53339. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53340. */
  53341. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53342. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53343. var u = segb.subtract(sega);
  53344. var v = rsegb.subtract(this.origin);
  53345. var w = sega.subtract(this.origin);
  53346. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53347. var b = BABYLON.Vector3.Dot(u, v);
  53348. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53349. var d = BABYLON.Vector3.Dot(u, w);
  53350. var e = BABYLON.Vector3.Dot(v, w);
  53351. var D = a * c - b * b; // always >= 0
  53352. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53353. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53354. // compute the line parameters of the two closest points
  53355. if (D < Ray.smallnum) {
  53356. sN = 0.0; // force using point P0 on segment S1
  53357. sD = 1.0; // to prevent possible division by 0.0 later
  53358. tN = e;
  53359. tD = c;
  53360. }
  53361. else {
  53362. sN = (b * e - c * d);
  53363. tN = (a * e - b * d);
  53364. if (sN < 0.0) {
  53365. sN = 0.0;
  53366. tN = e;
  53367. tD = c;
  53368. }
  53369. else if (sN > sD) {
  53370. sN = sD;
  53371. tN = e + b;
  53372. tD = c;
  53373. }
  53374. }
  53375. if (tN < 0.0) {
  53376. tN = 0.0;
  53377. // recompute sc for this edge
  53378. if (-d < 0.0) {
  53379. sN = 0.0;
  53380. }
  53381. else if (-d > a)
  53382. sN = sD;
  53383. else {
  53384. sN = -d;
  53385. sD = a;
  53386. }
  53387. }
  53388. else if (tN > tD) {
  53389. tN = tD;
  53390. // recompute sc for this edge
  53391. if ((-d + b) < 0.0) {
  53392. sN = 0;
  53393. }
  53394. else if ((-d + b) > a) {
  53395. sN = sD;
  53396. }
  53397. else {
  53398. sN = (-d + b);
  53399. sD = a;
  53400. }
  53401. }
  53402. // finally do the division to get sc and tc
  53403. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53404. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53405. // get the difference of the two closest points
  53406. var qtc = v.multiplyByFloats(tc, tc, tc);
  53407. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53408. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53409. if (isIntersected) {
  53410. return qtc.length();
  53411. }
  53412. return -1;
  53413. };
  53414. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53415. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53416. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53417. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53418. this.direction.normalize();
  53419. return this;
  53420. };
  53421. // Statics
  53422. Ray.Zero = function () {
  53423. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53424. };
  53425. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53426. var result = Ray.Zero();
  53427. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53428. };
  53429. /**
  53430. * 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
  53431. * transformed to the given world matrix.
  53432. * @param origin The origin point
  53433. * @param end The end point
  53434. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53435. */
  53436. Ray.CreateNewFromTo = function (origin, end, world) {
  53437. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53438. var direction = end.subtract(origin);
  53439. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53440. direction.normalize();
  53441. return Ray.Transform(new Ray(origin, direction, length), world);
  53442. };
  53443. Ray.Transform = function (ray, matrix) {
  53444. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53445. Ray.TransformToRef(ray, matrix, result);
  53446. return result;
  53447. };
  53448. Ray.TransformToRef = function (ray, matrix, result) {
  53449. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53450. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53451. result.length = ray.length;
  53452. var dir = result.direction;
  53453. var len = dir.length();
  53454. if (!(len === 0 || len === 1)) {
  53455. var num = 1.0 / len;
  53456. dir.x *= num;
  53457. dir.y *= num;
  53458. dir.z *= num;
  53459. result.length *= len;
  53460. }
  53461. };
  53462. Ray.smallnum = 0.00000001;
  53463. Ray.rayl = 10e8;
  53464. return Ray;
  53465. }());
  53466. BABYLON.Ray = Ray;
  53467. })(BABYLON || (BABYLON = {}));
  53468. //# sourceMappingURL=babylon.ray.js.map
  53469. "use strict";
  53470. var BABYLON;
  53471. (function (BABYLON) {
  53472. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53473. if (boxMin.x > sphereCenter.x + sphereRadius)
  53474. return false;
  53475. if (sphereCenter.x - sphereRadius > boxMax.x)
  53476. return false;
  53477. if (boxMin.y > sphereCenter.y + sphereRadius)
  53478. return false;
  53479. if (sphereCenter.y - sphereRadius > boxMax.y)
  53480. return false;
  53481. if (boxMin.z > sphereCenter.z + sphereRadius)
  53482. return false;
  53483. if (sphereCenter.z - sphereRadius > boxMax.z)
  53484. return false;
  53485. return true;
  53486. };
  53487. var getLowestRoot = (function () {
  53488. var result = { root: 0, found: false };
  53489. return function (a, b, c, maxR) {
  53490. result.root = 0;
  53491. result.found = false;
  53492. var determinant = b * b - 4.0 * a * c;
  53493. if (determinant < 0)
  53494. return result;
  53495. var sqrtD = Math.sqrt(determinant);
  53496. var r1 = (-b - sqrtD) / (2.0 * a);
  53497. var r2 = (-b + sqrtD) / (2.0 * a);
  53498. if (r1 > r2) {
  53499. var temp = r2;
  53500. r2 = r1;
  53501. r1 = temp;
  53502. }
  53503. if (r1 > 0 && r1 < maxR) {
  53504. result.root = r1;
  53505. result.found = true;
  53506. return result;
  53507. }
  53508. if (r2 > 0 && r2 < maxR) {
  53509. result.root = r2;
  53510. result.found = true;
  53511. return result;
  53512. }
  53513. return result;
  53514. };
  53515. })();
  53516. var Collider = /** @class */ (function () {
  53517. function Collider() {
  53518. this._collisionPoint = BABYLON.Vector3.Zero();
  53519. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  53520. this._tempVector = BABYLON.Vector3.Zero();
  53521. this._tempVector2 = BABYLON.Vector3.Zero();
  53522. this._tempVector3 = BABYLON.Vector3.Zero();
  53523. this._tempVector4 = BABYLON.Vector3.Zero();
  53524. this._edge = BABYLON.Vector3.Zero();
  53525. this._baseToVertex = BABYLON.Vector3.Zero();
  53526. this._destinationPoint = BABYLON.Vector3.Zero();
  53527. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  53528. this._displacementVector = BABYLON.Vector3.Zero();
  53529. this._radius = BABYLON.Vector3.One();
  53530. this._retry = 0;
  53531. this._basePointWorld = BABYLON.Vector3.Zero();
  53532. this._velocityWorld = BABYLON.Vector3.Zero();
  53533. this._normalizedVelocity = BABYLON.Vector3.Zero();
  53534. this._collisionMask = -1;
  53535. }
  53536. Object.defineProperty(Collider.prototype, "collisionMask", {
  53537. get: function () {
  53538. return this._collisionMask;
  53539. },
  53540. set: function (mask) {
  53541. this._collisionMask = !isNaN(mask) ? mask : -1;
  53542. },
  53543. enumerable: true,
  53544. configurable: true
  53545. });
  53546. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  53547. /**
  53548. * Gets the plane normal used to compute the sliding response (in local space)
  53549. */
  53550. get: function () {
  53551. return this._slidePlaneNormal;
  53552. },
  53553. enumerable: true,
  53554. configurable: true
  53555. });
  53556. // Methods
  53557. Collider.prototype._initialize = function (source, dir, e) {
  53558. this._velocity = dir;
  53559. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  53560. this._basePoint = source;
  53561. source.multiplyToRef(this._radius, this._basePointWorld);
  53562. dir.multiplyToRef(this._radius, this._velocityWorld);
  53563. this._velocityWorldLength = this._velocityWorld.length();
  53564. this._epsilon = e;
  53565. this.collisionFound = false;
  53566. };
  53567. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  53568. pa.subtractToRef(point, this._tempVector);
  53569. pb.subtractToRef(point, this._tempVector2);
  53570. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  53571. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53572. if (d < 0)
  53573. return false;
  53574. pc.subtractToRef(point, this._tempVector3);
  53575. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  53576. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53577. if (d < 0)
  53578. return false;
  53579. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  53580. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53581. return d >= 0;
  53582. };
  53583. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  53584. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  53585. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  53586. if (distance > this._velocityWorldLength + max + sphereRadius) {
  53587. return false;
  53588. }
  53589. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  53590. return false;
  53591. return true;
  53592. };
  53593. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  53594. var t0;
  53595. var embeddedInPlane = false;
  53596. //defensive programming, actually not needed.
  53597. if (!trianglePlaneArray) {
  53598. trianglePlaneArray = [];
  53599. }
  53600. if (!trianglePlaneArray[faceIndex]) {
  53601. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  53602. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  53603. }
  53604. var trianglePlane = trianglePlaneArray[faceIndex];
  53605. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  53606. return;
  53607. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  53608. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  53609. if (normalDotVelocity == 0) {
  53610. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  53611. return;
  53612. embeddedInPlane = true;
  53613. t0 = 0;
  53614. }
  53615. else {
  53616. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53617. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53618. if (t0 > t1) {
  53619. var temp = t1;
  53620. t1 = t0;
  53621. t0 = temp;
  53622. }
  53623. if (t0 > 1.0 || t1 < 0.0)
  53624. return;
  53625. if (t0 < 0)
  53626. t0 = 0;
  53627. if (t0 > 1.0)
  53628. t0 = 1.0;
  53629. }
  53630. this._collisionPoint.copyFromFloats(0, 0, 0);
  53631. var found = false;
  53632. var t = 1.0;
  53633. if (!embeddedInPlane) {
  53634. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  53635. this._velocity.scaleToRef(t0, this._tempVector);
  53636. this._planeIntersectionPoint.addInPlace(this._tempVector);
  53637. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  53638. found = true;
  53639. t = t0;
  53640. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  53641. }
  53642. }
  53643. if (!found) {
  53644. var velocitySquaredLength = this._velocity.lengthSquared();
  53645. var a = velocitySquaredLength;
  53646. this._basePoint.subtractToRef(p1, this._tempVector);
  53647. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53648. var c = this._tempVector.lengthSquared() - 1.0;
  53649. var lowestRoot = getLowestRoot(a, b, c, t);
  53650. if (lowestRoot.found) {
  53651. t = lowestRoot.root;
  53652. found = true;
  53653. this._collisionPoint.copyFrom(p1);
  53654. }
  53655. this._basePoint.subtractToRef(p2, this._tempVector);
  53656. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53657. c = this._tempVector.lengthSquared() - 1.0;
  53658. lowestRoot = getLowestRoot(a, b, c, t);
  53659. if (lowestRoot.found) {
  53660. t = lowestRoot.root;
  53661. found = true;
  53662. this._collisionPoint.copyFrom(p2);
  53663. }
  53664. this._basePoint.subtractToRef(p3, this._tempVector);
  53665. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53666. c = this._tempVector.lengthSquared() - 1.0;
  53667. lowestRoot = getLowestRoot(a, b, c, t);
  53668. if (lowestRoot.found) {
  53669. t = lowestRoot.root;
  53670. found = true;
  53671. this._collisionPoint.copyFrom(p3);
  53672. }
  53673. p2.subtractToRef(p1, this._edge);
  53674. p1.subtractToRef(this._basePoint, this._baseToVertex);
  53675. var edgeSquaredLength = this._edge.lengthSquared();
  53676. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53677. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53678. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53679. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53680. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53681. lowestRoot = getLowestRoot(a, b, c, t);
  53682. if (lowestRoot.found) {
  53683. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53684. if (f >= 0.0 && f <= 1.0) {
  53685. t = lowestRoot.root;
  53686. found = true;
  53687. this._edge.scaleInPlace(f);
  53688. p1.addToRef(this._edge, this._collisionPoint);
  53689. }
  53690. }
  53691. p3.subtractToRef(p2, this._edge);
  53692. p2.subtractToRef(this._basePoint, this._baseToVertex);
  53693. edgeSquaredLength = this._edge.lengthSquared();
  53694. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53695. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53696. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53697. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53698. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53699. lowestRoot = getLowestRoot(a, b, c, t);
  53700. if (lowestRoot.found) {
  53701. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53702. if (f >= 0.0 && f <= 1.0) {
  53703. t = lowestRoot.root;
  53704. found = true;
  53705. this._edge.scaleInPlace(f);
  53706. p2.addToRef(this._edge, this._collisionPoint);
  53707. }
  53708. }
  53709. p1.subtractToRef(p3, this._edge);
  53710. p3.subtractToRef(this._basePoint, this._baseToVertex);
  53711. edgeSquaredLength = this._edge.lengthSquared();
  53712. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53713. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53714. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53715. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53716. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53717. lowestRoot = getLowestRoot(a, b, c, t);
  53718. if (lowestRoot.found) {
  53719. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53720. if (f >= 0.0 && f <= 1.0) {
  53721. t = lowestRoot.root;
  53722. found = true;
  53723. this._edge.scaleInPlace(f);
  53724. p3.addToRef(this._edge, this._collisionPoint);
  53725. }
  53726. }
  53727. }
  53728. if (found) {
  53729. var distToCollision = t * this._velocity.length();
  53730. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  53731. if (!this.intersectionPoint) {
  53732. this.intersectionPoint = this._collisionPoint.clone();
  53733. }
  53734. else {
  53735. this.intersectionPoint.copyFrom(this._collisionPoint);
  53736. }
  53737. this._nearestDistance = distToCollision;
  53738. this.collisionFound = true;
  53739. }
  53740. }
  53741. };
  53742. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  53743. for (var i = indexStart; i < indexEnd; i += 3) {
  53744. var p1 = pts[indices[i] - decal];
  53745. var p2 = pts[indices[i + 1] - decal];
  53746. var p3 = pts[indices[i + 2] - decal];
  53747. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  53748. }
  53749. };
  53750. Collider.prototype._getResponse = function (pos, vel) {
  53751. pos.addToRef(vel, this._destinationPoint);
  53752. vel.scaleInPlace((this._nearestDistance / vel.length()));
  53753. this._basePoint.addToRef(vel, pos);
  53754. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  53755. this._slidePlaneNormal.normalize();
  53756. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  53757. pos.addInPlace(this._displacementVector);
  53758. this.intersectionPoint.addInPlace(this._displacementVector);
  53759. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  53760. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  53761. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  53762. };
  53763. return Collider;
  53764. }());
  53765. BABYLON.Collider = Collider;
  53766. })(BABYLON || (BABYLON = {}));
  53767. //# sourceMappingURL=babylon.collider.js.map
  53768. "use strict";
  53769. var BABYLON;
  53770. (function (BABYLON) {
  53771. //WebWorker code will be inserted to this variable.
  53772. BABYLON.CollisionWorker = "";
  53773. var WorkerTaskType;
  53774. (function (WorkerTaskType) {
  53775. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  53776. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  53777. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  53778. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  53779. var WorkerReplyType;
  53780. (function (WorkerReplyType) {
  53781. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  53782. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  53783. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  53784. var CollisionCoordinatorWorker = /** @class */ (function () {
  53785. function CollisionCoordinatorWorker() {
  53786. var _this = this;
  53787. this._scaledPosition = BABYLON.Vector3.Zero();
  53788. this._scaledVelocity = BABYLON.Vector3.Zero();
  53789. this.onMeshUpdated = function (transformNode) {
  53790. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  53791. };
  53792. this.onGeometryUpdated = function (geometry) {
  53793. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  53794. };
  53795. this._afterRender = function () {
  53796. if (!_this._init)
  53797. return;
  53798. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  53799. return;
  53800. }
  53801. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  53802. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  53803. if (_this._runningUpdated > 4) {
  53804. return;
  53805. }
  53806. ++_this._runningUpdated;
  53807. var payload = {
  53808. updatedMeshes: _this._addUpdateMeshesList,
  53809. updatedGeometries: _this._addUpdateGeometriesList,
  53810. removedGeometries: _this._toRemoveGeometryArray,
  53811. removedMeshes: _this._toRemoveMeshesArray
  53812. };
  53813. var message = {
  53814. payload: payload,
  53815. taskType: WorkerTaskType.UPDATE
  53816. };
  53817. var serializable = [];
  53818. for (var id in payload.updatedGeometries) {
  53819. if (payload.updatedGeometries.hasOwnProperty(id)) {
  53820. //prepare transferables
  53821. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  53822. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  53823. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  53824. }
  53825. }
  53826. _this._worker.postMessage(message, serializable);
  53827. _this._addUpdateMeshesList = {};
  53828. _this._addUpdateGeometriesList = {};
  53829. _this._toRemoveGeometryArray = [];
  53830. _this._toRemoveMeshesArray = [];
  53831. };
  53832. this._onMessageFromWorker = function (e) {
  53833. var returnData = e.data;
  53834. if (returnData.error != WorkerReplyType.SUCCESS) {
  53835. //TODO what errors can be returned from the worker?
  53836. BABYLON.Tools.Warn("error returned from worker!");
  53837. return;
  53838. }
  53839. switch (returnData.taskType) {
  53840. case WorkerTaskType.INIT:
  53841. _this._init = true;
  53842. //Update the worked with ALL of the scene's current state
  53843. _this._scene.meshes.forEach(function (mesh) {
  53844. _this.onMeshAdded(mesh);
  53845. });
  53846. _this._scene.getGeometries().forEach(function (geometry) {
  53847. _this.onGeometryAdded(geometry);
  53848. });
  53849. break;
  53850. case WorkerTaskType.UPDATE:
  53851. _this._runningUpdated--;
  53852. break;
  53853. case WorkerTaskType.COLLIDE:
  53854. var returnPayload = returnData.payload;
  53855. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  53856. return;
  53857. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  53858. if (callback) {
  53859. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  53860. if (mesh) {
  53861. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  53862. }
  53863. }
  53864. //cleanup
  53865. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  53866. break;
  53867. }
  53868. };
  53869. this._collisionsCallbackArray = [];
  53870. this._init = false;
  53871. this._runningUpdated = 0;
  53872. this._addUpdateMeshesList = {};
  53873. this._addUpdateGeometriesList = {};
  53874. this._toRemoveGeometryArray = [];
  53875. this._toRemoveMeshesArray = [];
  53876. }
  53877. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  53878. if (!this._init)
  53879. return;
  53880. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  53881. return;
  53882. position.divideToRef(collider._radius, this._scaledPosition);
  53883. displacement.divideToRef(collider._radius, this._scaledVelocity);
  53884. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  53885. var payload = {
  53886. collider: {
  53887. position: this._scaledPosition.asArray(),
  53888. velocity: this._scaledVelocity.asArray(),
  53889. radius: collider._radius.asArray()
  53890. },
  53891. collisionId: collisionIndex,
  53892. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  53893. maximumRetry: maximumRetry
  53894. };
  53895. var message = {
  53896. payload: payload,
  53897. taskType: WorkerTaskType.COLLIDE
  53898. };
  53899. this._worker.postMessage(message);
  53900. };
  53901. CollisionCoordinatorWorker.prototype.init = function (scene) {
  53902. this._scene = scene;
  53903. this._scene.registerAfterRender(this._afterRender);
  53904. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  53905. this._worker = new Worker(workerUrl);
  53906. this._worker.onmessage = this._onMessageFromWorker;
  53907. var message = {
  53908. payload: {},
  53909. taskType: WorkerTaskType.INIT
  53910. };
  53911. this._worker.postMessage(message);
  53912. };
  53913. CollisionCoordinatorWorker.prototype.destroy = function () {
  53914. this._scene.unregisterAfterRender(this._afterRender);
  53915. this._worker.terminate();
  53916. };
  53917. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  53918. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  53919. this.onMeshUpdated(mesh);
  53920. };
  53921. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  53922. this._toRemoveMeshesArray.push(mesh.uniqueId);
  53923. };
  53924. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  53925. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  53926. geometry.onGeometryUpdated = this.onGeometryUpdated;
  53927. this.onGeometryUpdated(geometry);
  53928. };
  53929. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  53930. this._toRemoveGeometryArray.push(geometry.id);
  53931. };
  53932. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  53933. var submeshes = [];
  53934. if (mesh.subMeshes) {
  53935. submeshes = mesh.subMeshes.map(function (sm, idx) {
  53936. var boundingInfo = sm.getBoundingInfo();
  53937. return {
  53938. position: idx,
  53939. verticesStart: sm.verticesStart,
  53940. verticesCount: sm.verticesCount,
  53941. indexStart: sm.indexStart,
  53942. indexCount: sm.indexCount,
  53943. hasMaterial: !!sm.getMaterial(),
  53944. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  53945. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  53946. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  53947. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  53948. };
  53949. });
  53950. }
  53951. var geometryId = null;
  53952. if (mesh instanceof BABYLON.Mesh) {
  53953. var geometry = mesh.geometry;
  53954. geometryId = geometry ? geometry.id : null;
  53955. }
  53956. else if (mesh instanceof BABYLON.InstancedMesh) {
  53957. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  53958. geometryId = geometry ? geometry.id : null;
  53959. }
  53960. var boundingInfo = mesh.getBoundingInfo();
  53961. return {
  53962. uniqueId: mesh.uniqueId,
  53963. id: mesh.id,
  53964. name: mesh.name,
  53965. geometryId: geometryId,
  53966. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  53967. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  53968. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  53969. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  53970. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  53971. subMeshes: submeshes,
  53972. checkCollisions: mesh.checkCollisions
  53973. };
  53974. };
  53975. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  53976. return {
  53977. id: geometry.id,
  53978. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  53979. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  53980. indices: new Uint32Array(geometry.getIndices() || []),
  53981. };
  53982. };
  53983. return CollisionCoordinatorWorker;
  53984. }());
  53985. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  53986. var CollisionCoordinatorLegacy = /** @class */ (function () {
  53987. function CollisionCoordinatorLegacy() {
  53988. this._scaledPosition = BABYLON.Vector3.Zero();
  53989. this._scaledVelocity = BABYLON.Vector3.Zero();
  53990. this._finalPosition = BABYLON.Vector3.Zero();
  53991. }
  53992. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  53993. position.divideToRef(collider._radius, this._scaledPosition);
  53994. displacement.divideToRef(collider._radius, this._scaledVelocity);
  53995. collider.collidedMesh = null;
  53996. collider._retry = 0;
  53997. collider._initialVelocity = this._scaledVelocity;
  53998. collider._initialPosition = this._scaledPosition;
  53999. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54000. this._finalPosition.multiplyInPlace(collider._radius);
  54001. //run the callback
  54002. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54003. };
  54004. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54005. this._scene = scene;
  54006. };
  54007. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54008. //Legacy need no destruction method.
  54009. };
  54010. //No update in legacy mode
  54011. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54012. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54013. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54014. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54015. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54016. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54017. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54018. if (excludedMesh === void 0) { excludedMesh = null; }
  54019. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54020. if (collider._retry >= maximumRetry) {
  54021. finalPosition.copyFrom(position);
  54022. return;
  54023. }
  54024. // Check if this is a mesh else camera or -1
  54025. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54026. collider._initialize(position, velocity, closeDistance);
  54027. // Check all meshes
  54028. for (var index = 0; index < this._scene.meshes.length; index++) {
  54029. var mesh = this._scene.meshes[index];
  54030. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54031. mesh._checkCollision(collider);
  54032. }
  54033. }
  54034. if (!collider.collisionFound) {
  54035. position.addToRef(velocity, finalPosition);
  54036. return;
  54037. }
  54038. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54039. collider._getResponse(position, velocity);
  54040. }
  54041. if (velocity.length() <= closeDistance) {
  54042. finalPosition.copyFrom(position);
  54043. return;
  54044. }
  54045. collider._retry++;
  54046. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54047. };
  54048. return CollisionCoordinatorLegacy;
  54049. }());
  54050. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54051. })(BABYLON || (BABYLON = {}));
  54052. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54053. "use strict";
  54054. var BABYLON;
  54055. (function (BABYLON) {
  54056. /**
  54057. * A particle represents one of the element emitted by a particle system.
  54058. * This is mainly define by its coordinates, direction, velocity and age.
  54059. */
  54060. var Particle = /** @class */ (function () {
  54061. /**
  54062. * Creates a new instance Particle
  54063. * @param particleSystem the particle system the particle belongs to
  54064. */
  54065. function Particle(
  54066. /**
  54067. * particleSystem the particle system the particle belongs to.
  54068. */
  54069. particleSystem) {
  54070. this.particleSystem = particleSystem;
  54071. /**
  54072. * The world position of the particle in the scene.
  54073. */
  54074. this.position = BABYLON.Vector3.Zero();
  54075. /**
  54076. * The world direction of the particle in the scene.
  54077. */
  54078. this.direction = BABYLON.Vector3.Zero();
  54079. /**
  54080. * The color of the particle.
  54081. */
  54082. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54083. /**
  54084. * The color change of the particle per step.
  54085. */
  54086. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54087. /**
  54088. * Defines how long will the life of the particle be.
  54089. */
  54090. this.lifeTime = 1.0;
  54091. /**
  54092. * The current age of the particle.
  54093. */
  54094. this.age = 0;
  54095. /**
  54096. * The current size of the particle.
  54097. */
  54098. this.size = 0;
  54099. /**
  54100. * The current angle of the particle.
  54101. */
  54102. this.angle = 0;
  54103. /**
  54104. * Defines how fast is the angle changing.
  54105. */
  54106. this.angularSpeed = 0;
  54107. /**
  54108. * Defines the cell index used by the particle to be rendered from a sprite.
  54109. */
  54110. this.cellIndex = 0;
  54111. this._currentFrameCounter = 0;
  54112. if (!this.particleSystem.isAnimationSheetEnabled) {
  54113. return;
  54114. }
  54115. this.updateCellInfoFromSystem();
  54116. }
  54117. Particle.prototype.updateCellInfoFromSystem = function () {
  54118. this.cellIndex = this.particleSystem.startSpriteCellID;
  54119. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54120. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54121. }
  54122. else {
  54123. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54124. }
  54125. };
  54126. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54127. // (ageOffset / scaledUpdateSpeed) / available cells
  54128. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54129. this._currentFrameCounter += scaledUpdateSpeed;
  54130. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54131. this._currentFrameCounter = 0;
  54132. this.cellIndex++;
  54133. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54134. this.cellIndex = this.particleSystem.endSpriteCellID;
  54135. }
  54136. }
  54137. };
  54138. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54139. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54140. this.cellIndex++;
  54141. this._currentFrameCounter = 0;
  54142. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54143. if (this.particleSystem.spriteCellLoop) {
  54144. this.cellIndex = this.particleSystem.startSpriteCellID;
  54145. }
  54146. else {
  54147. this.cellIndex = this.particleSystem.endSpriteCellID;
  54148. }
  54149. }
  54150. }
  54151. else {
  54152. this._currentFrameCounter++;
  54153. }
  54154. };
  54155. /**
  54156. * Copy the properties of particle to another one.
  54157. * @param other the particle to copy the information to.
  54158. */
  54159. Particle.prototype.copyTo = function (other) {
  54160. other.position.copyFrom(this.position);
  54161. other.direction.copyFrom(this.direction);
  54162. other.color.copyFrom(this.color);
  54163. other.colorStep.copyFrom(this.colorStep);
  54164. other.lifeTime = this.lifeTime;
  54165. other.age = this.age;
  54166. other.size = this.size;
  54167. other.angle = this.angle;
  54168. other.angularSpeed = this.angularSpeed;
  54169. other.particleSystem = this.particleSystem;
  54170. other.cellIndex = this.cellIndex;
  54171. };
  54172. return Particle;
  54173. }());
  54174. BABYLON.Particle = Particle;
  54175. })(BABYLON || (BABYLON = {}));
  54176. //# sourceMappingURL=babylon.particle.js.map
  54177. "use strict";
  54178. var BABYLON;
  54179. (function (BABYLON) {
  54180. /**
  54181. * This represents a particle system in Babylon.
  54182. * 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.
  54183. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54184. * @example https://doc.babylonjs.com/babylon101/particles
  54185. */
  54186. var ParticleSystem = /** @class */ (function () {
  54187. /**
  54188. * Instantiates a particle system.
  54189. * 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.
  54190. * @param name The name of the particle system
  54191. * @param capacity The max number of particles alive at the same time
  54192. * @param scene The scene the particle system belongs to
  54193. * @param customEffect a custom effect used to change the way particles are rendered by default
  54194. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54195. * @param epsilon Offset used to render the particles
  54196. */
  54197. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54198. if (customEffect === void 0) { customEffect = null; }
  54199. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54200. if (epsilon === void 0) { epsilon = 0.01; }
  54201. var _this = this;
  54202. /**
  54203. * List of animations used by the particle system.
  54204. */
  54205. this.animations = [];
  54206. /**
  54207. * The rendering group used by the Particle system to chose when to render.
  54208. */
  54209. this.renderingGroupId = 0;
  54210. /**
  54211. * The emitter represents the Mesh or position we are attaching the particle system to.
  54212. */
  54213. this.emitter = null;
  54214. /**
  54215. * The maximum number of particles to emit per frame
  54216. */
  54217. this.emitRate = 10;
  54218. /**
  54219. * If you want to launch only a few particles at once, that can be done, as well.
  54220. */
  54221. this.manualEmitCount = -1;
  54222. /**
  54223. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54224. */
  54225. this.updateSpeed = 0.01;
  54226. /**
  54227. * The amount of time the particle system is running (depends of the overall update speed).
  54228. */
  54229. this.targetStopDuration = 0;
  54230. /**
  54231. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54232. */
  54233. this.disposeOnStop = false;
  54234. /**
  54235. * Minimum power of emitting particles.
  54236. */
  54237. this.minEmitPower = 1;
  54238. /**
  54239. * Maximum power of emitting particles.
  54240. */
  54241. this.maxEmitPower = 1;
  54242. /**
  54243. * Minimum life time of emitting particles.
  54244. */
  54245. this.minLifeTime = 1;
  54246. /**
  54247. * Maximum life time of emitting particles.
  54248. */
  54249. this.maxLifeTime = 1;
  54250. /**
  54251. * Minimum Size of emitting particles.
  54252. */
  54253. this.minSize = 1;
  54254. /**
  54255. * Maximum Size of emitting particles.
  54256. */
  54257. this.maxSize = 1;
  54258. /**
  54259. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54260. */
  54261. this.minAngularSpeed = 0;
  54262. /**
  54263. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54264. */
  54265. this.maxAngularSpeed = 0;
  54266. /**
  54267. * The layer mask we are rendering the particles through.
  54268. */
  54269. this.layerMask = 0x0FFFFFFF;
  54270. /**
  54271. * This can help using your own shader to render the particle system.
  54272. * The according effect will be created
  54273. */
  54274. this.customShader = null;
  54275. /**
  54276. * By default particle system starts as soon as they are created. This prevents the
  54277. * automatic start to happen and let you decide when to start emitting particles.
  54278. */
  54279. this.preventAutoStart = false;
  54280. /**
  54281. * Callback triggered when the particle animation is ending.
  54282. */
  54283. this.onAnimationEnd = null;
  54284. /**
  54285. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54286. */
  54287. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54288. /**
  54289. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54290. * to override the particles.
  54291. */
  54292. this.forceDepthWrite = false;
  54293. /**
  54294. * You can use gravity if you want to give an orientation to your particles.
  54295. */
  54296. this.gravity = BABYLON.Vector3.Zero();
  54297. /**
  54298. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54299. */
  54300. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54301. /**
  54302. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54303. */
  54304. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54305. /**
  54306. * Color the particle will have at the end of its lifetime.
  54307. */
  54308. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54309. /**
  54310. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  54311. */
  54312. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54313. /**
  54314. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  54315. */
  54316. this.spriteCellLoop = true;
  54317. /**
  54318. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  54319. */
  54320. this.spriteCellChangeSpeed = 0;
  54321. /**
  54322. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  54323. */
  54324. this.startSpriteCellID = 0;
  54325. /**
  54326. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  54327. */
  54328. this.endSpriteCellID = 0;
  54329. /**
  54330. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  54331. */
  54332. this.spriteCellWidth = 0;
  54333. /**
  54334. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  54335. */
  54336. this.spriteCellHeight = 0;
  54337. /**
  54338. * An event triggered when the system is disposed.
  54339. */
  54340. this.onDisposeObservable = new BABYLON.Observable();
  54341. this._particles = new Array();
  54342. this._stockParticles = new Array();
  54343. this._newPartsExcess = 0;
  54344. this._vertexBuffers = {};
  54345. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54346. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54347. this._scaledDirection = BABYLON.Vector3.Zero();
  54348. this._scaledGravity = BABYLON.Vector3.Zero();
  54349. this._currentRenderId = -1;
  54350. this._started = false;
  54351. this._stopped = false;
  54352. this._actualFrame = 0;
  54353. this._vertexBufferSize = 11;
  54354. // start of sub system methods
  54355. /**
  54356. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54357. * Its lifetime will start back at 0.
  54358. */
  54359. this.recycleParticle = function (particle) {
  54360. var lastParticle = _this._particles.pop();
  54361. if (lastParticle !== particle) {
  54362. lastParticle.copyTo(particle);
  54363. }
  54364. _this._stockParticles.push(lastParticle);
  54365. };
  54366. this._createParticle = function () {
  54367. var particle;
  54368. if (_this._stockParticles.length !== 0) {
  54369. particle = _this._stockParticles.pop();
  54370. particle.age = 0;
  54371. particle.cellIndex = _this.startSpriteCellID;
  54372. }
  54373. else {
  54374. particle = new BABYLON.Particle(_this);
  54375. }
  54376. return particle;
  54377. };
  54378. this._emitFromParticle = function (particle) {
  54379. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54380. return;
  54381. }
  54382. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  54383. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  54384. subSystem._rootParticleSystem = _this;
  54385. _this.activeSubSystems.push(subSystem);
  54386. subSystem.start();
  54387. };
  54388. this._appendParticleVertexes = null;
  54389. this.id = name;
  54390. this.name = name;
  54391. this._capacity = capacity;
  54392. this._epsilon = epsilon;
  54393. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  54394. if (isAnimationSheetEnabled) {
  54395. this._vertexBufferSize = 12;
  54396. }
  54397. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54398. this._customEffect = customEffect;
  54399. scene.particleSystems.push(this);
  54400. this._createIndexBuffer();
  54401. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  54402. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  54403. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  54404. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  54405. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  54406. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  54407. if (this._isAnimationSheetEnabled) {
  54408. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  54409. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  54410. }
  54411. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54412. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54413. this._vertexBuffers["options"] = options;
  54414. // Default emitter type
  54415. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54416. this.updateFunction = function (particles) {
  54417. for (var index = 0; index < particles.length; index++) {
  54418. var particle = particles[index];
  54419. particle.age += _this._scaledUpdateSpeed;
  54420. if (particle.age >= particle.lifeTime) {
  54421. _this._emitFromParticle(particle);
  54422. _this.recycleParticle(particle);
  54423. index--;
  54424. continue;
  54425. }
  54426. else {
  54427. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54428. particle.color.addInPlace(_this._scaledColorStep);
  54429. if (particle.color.a < 0)
  54430. particle.color.a = 0;
  54431. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54432. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  54433. particle.position.addInPlace(_this._scaledDirection);
  54434. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54435. particle.direction.addInPlace(_this._scaledGravity);
  54436. if (_this._isAnimationSheetEnabled) {
  54437. particle.updateCellIndex(_this._scaledUpdateSpeed);
  54438. }
  54439. }
  54440. }
  54441. };
  54442. }
  54443. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54444. /**
  54445. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54446. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54447. */
  54448. get: function () {
  54449. if (this.particleEmitterType.direction1) {
  54450. return this.particleEmitterType.direction1;
  54451. }
  54452. return BABYLON.Vector3.Zero();
  54453. },
  54454. set: function (value) {
  54455. if (this.particleEmitterType.direction1) {
  54456. this.particleEmitterType.direction1 = value;
  54457. }
  54458. },
  54459. enumerable: true,
  54460. configurable: true
  54461. });
  54462. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54463. /**
  54464. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54465. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54466. */
  54467. get: function () {
  54468. if (this.particleEmitterType.direction2) {
  54469. return this.particleEmitterType.direction2;
  54470. }
  54471. return BABYLON.Vector3.Zero();
  54472. },
  54473. set: function (value) {
  54474. if (this.particleEmitterType.direction2) {
  54475. this.particleEmitterType.direction2 = value;
  54476. }
  54477. },
  54478. enumerable: true,
  54479. configurable: true
  54480. });
  54481. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  54482. /**
  54483. * 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.
  54484. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54485. */
  54486. get: function () {
  54487. if (this.particleEmitterType.minEmitBox) {
  54488. return this.particleEmitterType.minEmitBox;
  54489. }
  54490. return BABYLON.Vector3.Zero();
  54491. },
  54492. set: function (value) {
  54493. if (this.particleEmitterType.minEmitBox) {
  54494. this.particleEmitterType.minEmitBox = value;
  54495. }
  54496. },
  54497. enumerable: true,
  54498. configurable: true
  54499. });
  54500. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  54501. /**
  54502. * 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.
  54503. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54504. */
  54505. get: function () {
  54506. if (this.particleEmitterType.maxEmitBox) {
  54507. return this.particleEmitterType.maxEmitBox;
  54508. }
  54509. return BABYLON.Vector3.Zero();
  54510. },
  54511. set: function (value) {
  54512. if (this.particleEmitterType.maxEmitBox) {
  54513. this.particleEmitterType.maxEmitBox = value;
  54514. }
  54515. },
  54516. enumerable: true,
  54517. configurable: true
  54518. });
  54519. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  54520. /**
  54521. * Sets a callback that will be triggered when the system is disposed.
  54522. */
  54523. set: function (callback) {
  54524. if (this._onDisposeObserver) {
  54525. this.onDisposeObservable.remove(this._onDisposeObserver);
  54526. }
  54527. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54528. },
  54529. enumerable: true,
  54530. configurable: true
  54531. });
  54532. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  54533. /**
  54534. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  54535. */
  54536. get: function () {
  54537. return this._isAnimationSheetEnabled;
  54538. },
  54539. enumerable: true,
  54540. configurable: true
  54541. });
  54542. Object.defineProperty(ParticleSystem.prototype, "particles", {
  54543. //end of Sub-emitter
  54544. /**
  54545. * Gets the current list of active particles
  54546. */
  54547. get: function () {
  54548. return this._particles;
  54549. },
  54550. enumerable: true,
  54551. configurable: true
  54552. });
  54553. /**
  54554. * Returns the string "ParticleSystem"
  54555. * @returns a string containing the class name
  54556. */
  54557. ParticleSystem.prototype.getClassName = function () {
  54558. return "ParticleSystem";
  54559. };
  54560. ParticleSystem.prototype._createIndexBuffer = function () {
  54561. var indices = [];
  54562. var index = 0;
  54563. for (var count = 0; count < this._capacity; count++) {
  54564. indices.push(index);
  54565. indices.push(index + 1);
  54566. indices.push(index + 2);
  54567. indices.push(index);
  54568. indices.push(index + 2);
  54569. indices.push(index + 3);
  54570. index += 4;
  54571. }
  54572. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  54573. };
  54574. /**
  54575. * Gets the maximum number of particles active at the same time.
  54576. * @returns The max number of active particles.
  54577. */
  54578. ParticleSystem.prototype.getCapacity = function () {
  54579. return this._capacity;
  54580. };
  54581. /**
  54582. * Gets Wether there are still active particles in the system.
  54583. * @returns True if it is alive, otherwise false.
  54584. */
  54585. ParticleSystem.prototype.isAlive = function () {
  54586. return this._alive;
  54587. };
  54588. /**
  54589. * Gets Wether the system has been started.
  54590. * @returns True if it has been started, otherwise false.
  54591. */
  54592. ParticleSystem.prototype.isStarted = function () {
  54593. return this._started;
  54594. };
  54595. /**
  54596. * Starts the particle system and begins to emit.
  54597. */
  54598. ParticleSystem.prototype.start = function () {
  54599. this._started = true;
  54600. this._stopped = false;
  54601. this._actualFrame = 0;
  54602. if (this.subEmitters && this.subEmitters.length != 0) {
  54603. this.activeSubSystems = new Array();
  54604. }
  54605. };
  54606. /**
  54607. * Stops the particle system.
  54608. * @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.
  54609. */
  54610. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  54611. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  54612. this._stopped = true;
  54613. if (stopSubEmitters) {
  54614. this._stopSubEmitters();
  54615. }
  54616. };
  54617. // animation sheet
  54618. /**
  54619. * Remove all active particles
  54620. */
  54621. ParticleSystem.prototype.reset = function () {
  54622. this._stockParticles = [];
  54623. this._particles = [];
  54624. };
  54625. /**
  54626. * @ignore (for internal use only)
  54627. */
  54628. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  54629. var offset = index * this._vertexBufferSize;
  54630. this._vertexData[offset] = particle.position.x;
  54631. this._vertexData[offset + 1] = particle.position.y;
  54632. this._vertexData[offset + 2] = particle.position.z;
  54633. this._vertexData[offset + 3] = particle.color.r;
  54634. this._vertexData[offset + 4] = particle.color.g;
  54635. this._vertexData[offset + 5] = particle.color.b;
  54636. this._vertexData[offset + 6] = particle.color.a;
  54637. this._vertexData[offset + 7] = particle.angle;
  54638. this._vertexData[offset + 8] = particle.size;
  54639. this._vertexData[offset + 9] = offsetX;
  54640. this._vertexData[offset + 10] = offsetY;
  54641. };
  54642. /**
  54643. * @ignore (for internal use only)
  54644. */
  54645. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  54646. if (offsetX === 0)
  54647. offsetX = this._epsilon;
  54648. else if (offsetX === 1)
  54649. offsetX = 1 - this._epsilon;
  54650. if (offsetY === 0)
  54651. offsetY = this._epsilon;
  54652. else if (offsetY === 1)
  54653. offsetY = 1 - this._epsilon;
  54654. var offset = index * this._vertexBufferSize;
  54655. this._vertexData[offset] = particle.position.x;
  54656. this._vertexData[offset + 1] = particle.position.y;
  54657. this._vertexData[offset + 2] = particle.position.z;
  54658. this._vertexData[offset + 3] = particle.color.r;
  54659. this._vertexData[offset + 4] = particle.color.g;
  54660. this._vertexData[offset + 5] = particle.color.b;
  54661. this._vertexData[offset + 6] = particle.color.a;
  54662. this._vertexData[offset + 7] = particle.angle;
  54663. this._vertexData[offset + 8] = particle.size;
  54664. this._vertexData[offset + 9] = offsetX;
  54665. this._vertexData[offset + 10] = offsetY;
  54666. this._vertexData[offset + 11] = particle.cellIndex;
  54667. };
  54668. ParticleSystem.prototype._stopSubEmitters = function () {
  54669. if (!this.activeSubSystems) {
  54670. return;
  54671. }
  54672. this.activeSubSystems.forEach(function (subSystem) {
  54673. subSystem.stop(true);
  54674. });
  54675. this.activeSubSystems = new Array();
  54676. };
  54677. ParticleSystem.prototype._removeFromRoot = function () {
  54678. if (!this._rootParticleSystem) {
  54679. return;
  54680. }
  54681. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  54682. if (index !== -1) {
  54683. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  54684. }
  54685. };
  54686. // end of sub system methods
  54687. ParticleSystem.prototype._update = function (newParticles) {
  54688. // Update current
  54689. this._alive = this._particles.length > 0;
  54690. this.updateFunction(this._particles);
  54691. // Add new ones
  54692. var worldMatrix;
  54693. if (this.emitter.position) {
  54694. var emitterMesh = this.emitter;
  54695. worldMatrix = emitterMesh.getWorldMatrix();
  54696. }
  54697. else {
  54698. var emitterPosition = this.emitter;
  54699. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  54700. }
  54701. var particle;
  54702. for (var index = 0; index < newParticles; index++) {
  54703. if (this._particles.length === this._capacity) {
  54704. break;
  54705. }
  54706. particle = this._createParticle();
  54707. this._particles.push(particle);
  54708. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  54709. if (this.startPositionFunction) {
  54710. this.startPositionFunction(worldMatrix, particle.position, particle);
  54711. }
  54712. else {
  54713. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  54714. }
  54715. if (this.startDirectionFunction) {
  54716. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  54717. }
  54718. else {
  54719. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  54720. }
  54721. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  54722. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  54723. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  54724. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  54725. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  54726. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  54727. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  54728. }
  54729. };
  54730. ParticleSystem.prototype._getEffect = function () {
  54731. if (this._customEffect) {
  54732. return this._customEffect;
  54733. }
  54734. ;
  54735. var defines = [];
  54736. if (this._scene.clipPlane) {
  54737. defines.push("#define CLIPPLANE");
  54738. }
  54739. if (this._isAnimationSheetEnabled) {
  54740. defines.push("#define ANIMATESHEET");
  54741. }
  54742. // Effect
  54743. var join = defines.join("\n");
  54744. if (this._cachedDefines !== join) {
  54745. this._cachedDefines = join;
  54746. var attributesNamesOrOptions;
  54747. var effectCreationOption;
  54748. if (this._isAnimationSheetEnabled) {
  54749. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  54750. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  54751. }
  54752. else {
  54753. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  54754. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  54755. }
  54756. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  54757. }
  54758. return this._effect;
  54759. };
  54760. /**
  54761. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  54762. */
  54763. ParticleSystem.prototype.animate = function () {
  54764. if (!this._started)
  54765. return;
  54766. var effect = this._getEffect();
  54767. // Check
  54768. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  54769. return;
  54770. if (this._currentRenderId === this._scene.getRenderId()) {
  54771. return;
  54772. }
  54773. this._currentRenderId = this._scene.getRenderId();
  54774. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  54775. // determine the number of particles we need to create
  54776. var newParticles;
  54777. if (this.manualEmitCount > -1) {
  54778. newParticles = this.manualEmitCount;
  54779. this._newPartsExcess = 0;
  54780. this.manualEmitCount = 0;
  54781. }
  54782. else {
  54783. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  54784. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  54785. }
  54786. if (this._newPartsExcess > 1.0) {
  54787. newParticles += this._newPartsExcess >> 0;
  54788. this._newPartsExcess -= this._newPartsExcess >> 0;
  54789. }
  54790. this._alive = false;
  54791. if (!this._stopped) {
  54792. this._actualFrame += this._scaledUpdateSpeed;
  54793. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  54794. this.stop();
  54795. }
  54796. else {
  54797. newParticles = 0;
  54798. }
  54799. this._update(newParticles);
  54800. // Stopped?
  54801. if (this._stopped) {
  54802. if (!this._alive) {
  54803. this._started = false;
  54804. if (this.onAnimationEnd) {
  54805. this.onAnimationEnd();
  54806. }
  54807. if (this.disposeOnStop) {
  54808. this._scene._toBeDisposed.push(this);
  54809. }
  54810. }
  54811. }
  54812. // Animation sheet
  54813. if (this._isAnimationSheetEnabled) {
  54814. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  54815. }
  54816. else {
  54817. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  54818. }
  54819. // Update VBO
  54820. var offset = 0;
  54821. for (var index = 0; index < this._particles.length; index++) {
  54822. var particle = this._particles[index];
  54823. this._appendParticleVertexes(offset, particle);
  54824. offset += 4;
  54825. }
  54826. if (this._vertexBuffer) {
  54827. this._vertexBuffer.update(this._vertexData);
  54828. }
  54829. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  54830. this.stop();
  54831. }
  54832. };
  54833. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  54834. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  54835. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  54836. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  54837. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  54838. };
  54839. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  54840. this._appendParticleVertex(offset++, particle, 0, 0);
  54841. this._appendParticleVertex(offset++, particle, 1, 0);
  54842. this._appendParticleVertex(offset++, particle, 1, 1);
  54843. this._appendParticleVertex(offset++, particle, 0, 1);
  54844. };
  54845. /**
  54846. * Rebuilds the particle system.
  54847. */
  54848. ParticleSystem.prototype.rebuild = function () {
  54849. this._createIndexBuffer();
  54850. if (this._vertexBuffer) {
  54851. this._vertexBuffer._rebuild();
  54852. }
  54853. };
  54854. /**
  54855. * Is this system ready to be used/rendered
  54856. * @return true if the system is ready
  54857. */
  54858. ParticleSystem.prototype.isReady = function () {
  54859. var effect = this._getEffect();
  54860. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  54861. return false;
  54862. }
  54863. return true;
  54864. };
  54865. /**
  54866. * Renders the particle system in its current state.
  54867. * @returns the current number of particles
  54868. */
  54869. ParticleSystem.prototype.render = function () {
  54870. var effect = this._getEffect();
  54871. // Check
  54872. if (!this.isReady() || !this._particles.length) {
  54873. return 0;
  54874. }
  54875. var engine = this._scene.getEngine();
  54876. // Render
  54877. engine.enableEffect(effect);
  54878. engine.setState(false);
  54879. var viewMatrix = this._scene.getViewMatrix();
  54880. effect.setTexture("diffuseSampler", this.particleTexture);
  54881. effect.setMatrix("view", viewMatrix);
  54882. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54883. if (this._isAnimationSheetEnabled && this.particleTexture) {
  54884. var baseSize = this.particleTexture.getBaseSize();
  54885. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  54886. }
  54887. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  54888. if (this._scene.clipPlane) {
  54889. var clipPlane = this._scene.clipPlane;
  54890. var invView = viewMatrix.clone();
  54891. invView.invert();
  54892. effect.setMatrix("invView", invView);
  54893. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  54894. }
  54895. // VBOs
  54896. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54897. // Draw order
  54898. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  54899. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  54900. }
  54901. else {
  54902. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54903. }
  54904. if (this.forceDepthWrite) {
  54905. engine.setDepthWrite(true);
  54906. }
  54907. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  54908. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54909. return this._particles.length;
  54910. };
  54911. /**
  54912. * Disposes the particle system and free the associated resources
  54913. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  54914. */
  54915. ParticleSystem.prototype.dispose = function (disposeTexture) {
  54916. if (disposeTexture === void 0) { disposeTexture = true; }
  54917. if (this._vertexBuffer) {
  54918. this._vertexBuffer.dispose();
  54919. this._vertexBuffer = null;
  54920. }
  54921. if (this._indexBuffer) {
  54922. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54923. this._indexBuffer = null;
  54924. }
  54925. if (disposeTexture && this.particleTexture) {
  54926. this.particleTexture.dispose();
  54927. this.particleTexture = null;
  54928. }
  54929. this._removeFromRoot();
  54930. // Remove from scene
  54931. var index = this._scene.particleSystems.indexOf(this);
  54932. if (index > -1) {
  54933. this._scene.particleSystems.splice(index, 1);
  54934. }
  54935. // Callback
  54936. this.onDisposeObservable.notifyObservers(this);
  54937. this.onDisposeObservable.clear();
  54938. };
  54939. /**
  54940. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  54941. * @param radius The radius of the sphere to emit from
  54942. * @returns the emitter
  54943. */
  54944. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  54945. if (radius === void 0) { radius = 1; }
  54946. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  54947. this.particleEmitterType = particleEmitter;
  54948. return particleEmitter;
  54949. };
  54950. /**
  54951. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  54952. * @param radius The radius of the sphere to emit from
  54953. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  54954. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  54955. * @returns the emitter
  54956. */
  54957. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  54958. if (radius === void 0) { radius = 1; }
  54959. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  54960. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  54961. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  54962. this.particleEmitterType = particleEmitter;
  54963. return particleEmitter;
  54964. };
  54965. /**
  54966. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  54967. * @param radius The radius of the cone to emit from
  54968. * @param angle The base angle of the cone
  54969. * @returns the emitter
  54970. */
  54971. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  54972. if (radius === void 0) { radius = 1; }
  54973. if (angle === void 0) { angle = Math.PI / 4; }
  54974. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  54975. this.particleEmitterType = particleEmitter;
  54976. return particleEmitter;
  54977. };
  54978. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  54979. /**
  54980. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  54981. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  54982. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  54983. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  54984. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  54985. * @returns the emitter
  54986. */
  54987. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  54988. var particleEmitter = new BABYLON.BoxParticleEmitter();
  54989. this.particleEmitterType = particleEmitter;
  54990. this.direction1 = direction1;
  54991. this.direction2 = direction2;
  54992. this.minEmitBox = minEmitBox;
  54993. this.maxEmitBox = maxEmitBox;
  54994. return particleEmitter;
  54995. };
  54996. // Clone
  54997. /**
  54998. * Clones the particle system.
  54999. * @param name The name of the cloned object
  55000. * @param newEmitter The new emitter to use
  55001. * @returns the cloned particle system
  55002. */
  55003. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55004. var custom = null;
  55005. var program = null;
  55006. if (this.customShader != null) {
  55007. program = this.customShader;
  55008. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55009. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55010. }
  55011. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55012. result.customShader = program;
  55013. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55014. if (newEmitter === undefined) {
  55015. newEmitter = this.emitter;
  55016. }
  55017. result.emitter = newEmitter;
  55018. if (this.particleTexture) {
  55019. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55020. }
  55021. if (!this.preventAutoStart) {
  55022. result.start();
  55023. }
  55024. return result;
  55025. };
  55026. /**
  55027. * Serializes the particle system to a JSON object.
  55028. * @returns the JSON object
  55029. */
  55030. ParticleSystem.prototype.serialize = function () {
  55031. var serializationObject = {};
  55032. serializationObject.name = this.name;
  55033. serializationObject.id = this.id;
  55034. // Emitter
  55035. if (this.emitter.position) {
  55036. var emitterMesh = this.emitter;
  55037. serializationObject.emitterId = emitterMesh.id;
  55038. }
  55039. else {
  55040. var emitterPosition = this.emitter;
  55041. serializationObject.emitter = emitterPosition.asArray();
  55042. }
  55043. serializationObject.capacity = this.getCapacity();
  55044. if (this.particleTexture) {
  55045. serializationObject.textureName = this.particleTexture.name;
  55046. }
  55047. // Animations
  55048. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55049. // Particle system
  55050. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55051. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55052. serializationObject.minSize = this.minSize;
  55053. serializationObject.maxSize = this.maxSize;
  55054. serializationObject.minEmitPower = this.minEmitPower;
  55055. serializationObject.maxEmitPower = this.maxEmitPower;
  55056. serializationObject.minLifeTime = this.minLifeTime;
  55057. serializationObject.maxLifeTime = this.maxLifeTime;
  55058. serializationObject.emitRate = this.emitRate;
  55059. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55060. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55061. serializationObject.gravity = this.gravity.asArray();
  55062. serializationObject.direction1 = this.direction1.asArray();
  55063. serializationObject.direction2 = this.direction2.asArray();
  55064. serializationObject.color1 = this.color1.asArray();
  55065. serializationObject.color2 = this.color2.asArray();
  55066. serializationObject.colorDead = this.colorDead.asArray();
  55067. serializationObject.updateSpeed = this.updateSpeed;
  55068. serializationObject.targetStopDuration = this.targetStopDuration;
  55069. serializationObject.textureMask = this.textureMask.asArray();
  55070. serializationObject.blendMode = this.blendMode;
  55071. serializationObject.customShader = this.customShader;
  55072. serializationObject.preventAutoStart = this.preventAutoStart;
  55073. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55074. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55075. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55076. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55077. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55078. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55079. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55080. // Emitter
  55081. if (this.particleEmitterType) {
  55082. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55083. }
  55084. return serializationObject;
  55085. };
  55086. /**
  55087. * Parses a JSON object to create a particle system.
  55088. * @param parsedParticleSystem The JSON object to parse
  55089. * @param scene The scene to create the particle system in
  55090. * @param rootUrl The root url to use to load external dependencies like texture
  55091. * @returns the Parsed particle system
  55092. */
  55093. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55094. var name = parsedParticleSystem.name;
  55095. var custom = null;
  55096. var program = null;
  55097. if (parsedParticleSystem.customShader) {
  55098. program = parsedParticleSystem.customShader;
  55099. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55100. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55101. }
  55102. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  55103. particleSystem.customShader = program;
  55104. if (parsedParticleSystem.id) {
  55105. particleSystem.id = parsedParticleSystem.id;
  55106. }
  55107. // Auto start
  55108. if (parsedParticleSystem.preventAutoStart) {
  55109. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  55110. }
  55111. // Texture
  55112. if (parsedParticleSystem.textureName) {
  55113. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55114. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55115. }
  55116. // Emitter
  55117. if (parsedParticleSystem.emitterId) {
  55118. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55119. }
  55120. else {
  55121. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55122. }
  55123. // Animations
  55124. if (parsedParticleSystem.animations) {
  55125. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55126. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55127. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55128. }
  55129. }
  55130. if (parsedParticleSystem.autoAnimate) {
  55131. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  55132. }
  55133. // Particle system
  55134. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  55135. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  55136. particleSystem.minSize = parsedParticleSystem.minSize;
  55137. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55138. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55139. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55140. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55141. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55142. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55143. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  55144. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  55145. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55146. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  55147. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  55148. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55149. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55150. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55151. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55152. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55153. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  55154. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55155. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  55156. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  55157. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  55158. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  55159. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  55160. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  55161. if (!particleSystem.preventAutoStart) {
  55162. particleSystem.start();
  55163. }
  55164. return particleSystem;
  55165. };
  55166. /**
  55167. * Source color is added to the destination color without alpha affecting the result.
  55168. */
  55169. ParticleSystem.BLENDMODE_ONEONE = 0;
  55170. /**
  55171. * Blend current color and particle color using particle’s alpha.
  55172. */
  55173. ParticleSystem.BLENDMODE_STANDARD = 1;
  55174. return ParticleSystem;
  55175. }());
  55176. BABYLON.ParticleSystem = ParticleSystem;
  55177. })(BABYLON || (BABYLON = {}));
  55178. //# sourceMappingURL=babylon.particleSystem.js.map
  55179. "use strict";
  55180. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  55181. "use strict";
  55182. var BABYLON;
  55183. (function (BABYLON) {
  55184. /**
  55185. * Particle emitter emitting particles from the inside of a box.
  55186. * It emits the particles randomly between 2 given directions.
  55187. */
  55188. var BoxParticleEmitter = /** @class */ (function () {
  55189. /**
  55190. * Creates a new instance BoxParticleEmitter
  55191. */
  55192. function BoxParticleEmitter() {
  55193. /**
  55194. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55195. */
  55196. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  55197. /**
  55198. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55199. */
  55200. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  55201. /**
  55202. * 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.
  55203. */
  55204. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  55205. /**
  55206. * 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.
  55207. */
  55208. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  55209. }
  55210. /**
  55211. * Called by the particle System when the direction is computed for the created particle.
  55212. * @param emitPower is the power of the particle (speed)
  55213. * @param worldMatrix is the world matrix of the particle system
  55214. * @param directionToUpdate is the direction vector to update with the result
  55215. * @param particle is the particle we are computed the direction for
  55216. */
  55217. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55218. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55219. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55220. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55221. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55222. };
  55223. /**
  55224. * Called by the particle System when the position is computed for the created particle.
  55225. * @param worldMatrix is the world matrix of the particle system
  55226. * @param positionToUpdate is the position vector to update with the result
  55227. * @param particle is the particle we are computed the position for
  55228. */
  55229. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55230. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  55231. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  55232. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  55233. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55234. };
  55235. /**
  55236. * Clones the current emitter and returns a copy of it
  55237. * @returns the new emitter
  55238. */
  55239. BoxParticleEmitter.prototype.clone = function () {
  55240. var newOne = new BoxParticleEmitter();
  55241. BABYLON.Tools.DeepCopy(this, newOne);
  55242. return newOne;
  55243. };
  55244. /**
  55245. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55246. * @param effect defines the update shader
  55247. */
  55248. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  55249. effect.setVector3("direction1", this.direction1);
  55250. effect.setVector3("direction2", this.direction2);
  55251. effect.setVector3("minEmitBox", this.minEmitBox);
  55252. effect.setVector3("maxEmitBox", this.maxEmitBox);
  55253. };
  55254. /**
  55255. * Returns a string to use to update the GPU particles update shader
  55256. * @returns a string containng the defines string
  55257. */
  55258. BoxParticleEmitter.prototype.getEffectDefines = function () {
  55259. return "#define BOXEMITTER";
  55260. };
  55261. /**
  55262. * Returns the string "BoxEmitter"
  55263. * @returns a string containing the class name
  55264. */
  55265. BoxParticleEmitter.prototype.getClassName = function () {
  55266. return "BoxEmitter";
  55267. };
  55268. /**
  55269. * Serializes the particle system to a JSON object.
  55270. * @returns the JSON object
  55271. */
  55272. BoxParticleEmitter.prototype.serialize = function () {
  55273. var serializationObject = {};
  55274. serializationObject.type = this.getClassName();
  55275. serializationObject.direction1 = this.direction1.asArray();
  55276. ;
  55277. serializationObject.direction2 = this.direction2.asArray();
  55278. ;
  55279. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55280. ;
  55281. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55282. ;
  55283. return serializationObject;
  55284. };
  55285. /**
  55286. * Parse properties from a JSON object
  55287. * @param serializationObject defines the JSON object
  55288. */
  55289. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  55290. this.direction1.copyFrom(serializationObject.direction1);
  55291. this.direction2.copyFrom(serializationObject.direction2);
  55292. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  55293. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  55294. };
  55295. return BoxParticleEmitter;
  55296. }());
  55297. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  55298. })(BABYLON || (BABYLON = {}));
  55299. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  55300. "use strict";
  55301. var BABYLON;
  55302. (function (BABYLON) {
  55303. /**
  55304. * Particle emitter emitting particles from the inside of a cone.
  55305. * It emits the particles alongside the cone volume from the base to the particle.
  55306. * The emission direction might be randomized.
  55307. */
  55308. var ConeParticleEmitter = /** @class */ (function () {
  55309. /**
  55310. * Creates a new instance ConeParticleEmitter
  55311. * @param radius the radius of the emission cone (1 by default)
  55312. * @param angles the cone base angle (PI by default)
  55313. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55314. */
  55315. function ConeParticleEmitter(radius,
  55316. /**
  55317. * The radius of the emission cone.
  55318. */
  55319. angle,
  55320. /**
  55321. * The cone base angle.
  55322. */
  55323. directionRandomizer) {
  55324. if (radius === void 0) { radius = 1; }
  55325. if (angle === void 0) { angle = Math.PI; }
  55326. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55327. this.angle = angle;
  55328. this.directionRandomizer = directionRandomizer;
  55329. this.radius = radius;
  55330. }
  55331. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  55332. /**
  55333. * Gets the radius of the emission cone.
  55334. */
  55335. get: function () {
  55336. return this._radius;
  55337. },
  55338. /**
  55339. * Sets the radius of the emission cone.
  55340. */
  55341. set: function (value) {
  55342. this._radius = value;
  55343. if (this.angle !== 0) {
  55344. this._height = value / Math.tan(this.angle / 2);
  55345. }
  55346. else {
  55347. this._height = 1;
  55348. }
  55349. },
  55350. enumerable: true,
  55351. configurable: true
  55352. });
  55353. /**
  55354. * Called by the particle System when the direction is computed for the created particle.
  55355. * @param emitPower is the power of the particle (speed)
  55356. * @param worldMatrix is the world matrix of the particle system
  55357. * @param directionToUpdate is the direction vector to update with the result
  55358. * @param particle is the particle we are computed the direction for
  55359. */
  55360. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55361. if (this.angle === 0) {
  55362. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  55363. }
  55364. else {
  55365. // measure the direction Vector from the emitter to the particle.
  55366. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55367. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55368. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55369. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55370. direction.x += randX;
  55371. direction.y += randY;
  55372. direction.z += randZ;
  55373. direction.normalize();
  55374. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55375. }
  55376. };
  55377. /**
  55378. * Called by the particle System when the position is computed for the created particle.
  55379. * @param worldMatrix is the world matrix of the particle system
  55380. * @param positionToUpdate is the position vector to update with the result
  55381. * @param particle is the particle we are computed the position for
  55382. */
  55383. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55384. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  55385. var h = BABYLON.Scalar.RandomRange(0, 1);
  55386. // Better distribution in a cone at normal angles.
  55387. h = 1 - h * h;
  55388. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  55389. radius = radius * h;
  55390. var randX = radius * Math.sin(s);
  55391. var randZ = radius * Math.cos(s);
  55392. var randY = h * this._height;
  55393. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55394. };
  55395. /**
  55396. * Clones the current emitter and returns a copy of it
  55397. * @returns the new emitter
  55398. */
  55399. ConeParticleEmitter.prototype.clone = function () {
  55400. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  55401. BABYLON.Tools.DeepCopy(this, newOne);
  55402. return newOne;
  55403. };
  55404. /**
  55405. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55406. * @param effect defines the update shader
  55407. */
  55408. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  55409. effect.setFloat("radius", this.radius);
  55410. effect.setFloat("angle", this.angle);
  55411. effect.setFloat("height", this._height);
  55412. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55413. };
  55414. /**
  55415. * Returns a string to use to update the GPU particles update shader
  55416. * @returns a string containng the defines string
  55417. */
  55418. ConeParticleEmitter.prototype.getEffectDefines = function () {
  55419. return "#define CONEEMITTER";
  55420. };
  55421. /**
  55422. * Returns the string "BoxEmitter"
  55423. * @returns a string containing the class name
  55424. */
  55425. ConeParticleEmitter.prototype.getClassName = function () {
  55426. return "ConeEmitter";
  55427. };
  55428. /**
  55429. * Serializes the particle system to a JSON object.
  55430. * @returns the JSON object
  55431. */
  55432. ConeParticleEmitter.prototype.serialize = function () {
  55433. var serializationObject = {};
  55434. serializationObject.type = this.getClassName();
  55435. serializationObject.radius = this.radius;
  55436. serializationObject.angle = this.angle;
  55437. serializationObject.directionRandomizer = this.directionRandomizer;
  55438. return serializationObject;
  55439. };
  55440. /**
  55441. * Parse properties from a JSON object
  55442. * @param serializationObject defines the JSON object
  55443. */
  55444. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  55445. this.radius = serializationObject.radius;
  55446. this.angle = serializationObject.angle;
  55447. this.directionRandomizer = serializationObject.directionRandomizer;
  55448. };
  55449. return ConeParticleEmitter;
  55450. }());
  55451. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  55452. })(BABYLON || (BABYLON = {}));
  55453. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  55454. "use strict";
  55455. var BABYLON;
  55456. (function (BABYLON) {
  55457. /**
  55458. * Particle emitter emitting particles from the inside of a sphere.
  55459. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  55460. */
  55461. var SphereParticleEmitter = /** @class */ (function () {
  55462. /**
  55463. * Creates a new instance SphereParticleEmitter
  55464. * @param radius the radius of the emission sphere (1 by default)
  55465. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55466. */
  55467. function SphereParticleEmitter(
  55468. /**
  55469. * The radius of the emission sphere.
  55470. */
  55471. radius,
  55472. /**
  55473. * How much to randomize the particle direction [0-1].
  55474. */
  55475. directionRandomizer) {
  55476. if (radius === void 0) { radius = 1; }
  55477. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55478. this.radius = radius;
  55479. this.directionRandomizer = directionRandomizer;
  55480. }
  55481. /**
  55482. * Called by the particle System when the direction is computed for the created particle.
  55483. * @param emitPower is the power of the particle (speed)
  55484. * @param worldMatrix is the world matrix of the particle system
  55485. * @param directionToUpdate is the direction vector to update with the result
  55486. * @param particle is the particle we are computed the direction for
  55487. */
  55488. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55489. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55490. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55491. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55492. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55493. direction.x += randX;
  55494. direction.y += randY;
  55495. direction.z += randZ;
  55496. direction.normalize();
  55497. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55498. };
  55499. /**
  55500. * Called by the particle System when the position is computed for the created particle.
  55501. * @param worldMatrix is the world matrix of the particle system
  55502. * @param positionToUpdate is the position vector to update with the result
  55503. * @param particle is the particle we are computed the position for
  55504. */
  55505. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55506. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  55507. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  55508. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  55509. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  55510. var randY = randRadius * Math.cos(theta);
  55511. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  55512. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55513. };
  55514. /**
  55515. * Clones the current emitter and returns a copy of it
  55516. * @returns the new emitter
  55517. */
  55518. SphereParticleEmitter.prototype.clone = function () {
  55519. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  55520. BABYLON.Tools.DeepCopy(this, newOne);
  55521. return newOne;
  55522. };
  55523. /**
  55524. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55525. * @param effect defines the update shader
  55526. */
  55527. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  55528. effect.setFloat("radius", this.radius);
  55529. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55530. };
  55531. /**
  55532. * Returns a string to use to update the GPU particles update shader
  55533. * @returns a string containng the defines string
  55534. */
  55535. SphereParticleEmitter.prototype.getEffectDefines = function () {
  55536. return "#define SPHEREEMITTER";
  55537. };
  55538. /**
  55539. * Returns the string "SphereParticleEmitter"
  55540. * @returns a string containing the class name
  55541. */
  55542. SphereParticleEmitter.prototype.getClassName = function () {
  55543. return "SphereParticleEmitter";
  55544. };
  55545. /**
  55546. * Serializes the particle system to a JSON object.
  55547. * @returns the JSON object
  55548. */
  55549. SphereParticleEmitter.prototype.serialize = function () {
  55550. var serializationObject = {};
  55551. serializationObject.type = this.getClassName();
  55552. serializationObject.radius = this.radius;
  55553. serializationObject.directionRandomizer = this.directionRandomizer;
  55554. return serializationObject;
  55555. };
  55556. /**
  55557. * Parse properties from a JSON object
  55558. * @param serializationObject defines the JSON object
  55559. */
  55560. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  55561. this.radius = serializationObject.radius;
  55562. this.directionRandomizer = serializationObject.directionRandomizer;
  55563. };
  55564. return SphereParticleEmitter;
  55565. }());
  55566. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  55567. /**
  55568. * Particle emitter emitting particles from the inside of a sphere.
  55569. * It emits the particles randomly between two vectors.
  55570. */
  55571. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  55572. __extends(SphereDirectedParticleEmitter, _super);
  55573. /**
  55574. * Creates a new instance SphereDirectedParticleEmitter
  55575. * @param radius the radius of the emission sphere (1 by default)
  55576. * @param direction1 the min limit of the emission direction (up vector by default)
  55577. * @param direction2 the max limit of the emission direction (up vector by default)
  55578. */
  55579. function SphereDirectedParticleEmitter(radius,
  55580. /**
  55581. * The min limit of the emission direction.
  55582. */
  55583. direction1,
  55584. /**
  55585. * The max limit of the emission direction.
  55586. */
  55587. direction2) {
  55588. if (radius === void 0) { radius = 1; }
  55589. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  55590. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  55591. var _this = _super.call(this, radius) || this;
  55592. _this.direction1 = direction1;
  55593. _this.direction2 = direction2;
  55594. return _this;
  55595. }
  55596. /**
  55597. * Called by the particle System when the direction is computed for the created particle.
  55598. * @param emitPower is the power of the particle (speed)
  55599. * @param worldMatrix is the world matrix of the particle system
  55600. * @param directionToUpdate is the direction vector to update with the result
  55601. * @param particle is the particle we are computed the direction for
  55602. */
  55603. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55604. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55605. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55606. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55607. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55608. };
  55609. /**
  55610. * Clones the current emitter and returns a copy of it
  55611. * @returns the new emitter
  55612. */
  55613. SphereDirectedParticleEmitter.prototype.clone = function () {
  55614. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  55615. BABYLON.Tools.DeepCopy(this, newOne);
  55616. return newOne;
  55617. };
  55618. /**
  55619. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55620. * @param effect defines the update shader
  55621. */
  55622. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  55623. effect.setFloat("radius", this.radius);
  55624. effect.setVector3("direction1", this.direction1);
  55625. effect.setVector3("direction2", this.direction2);
  55626. };
  55627. /**
  55628. * Returns a string to use to update the GPU particles update shader
  55629. * @returns a string containng the defines string
  55630. */
  55631. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  55632. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  55633. };
  55634. /**
  55635. * Returns the string "SphereDirectedParticleEmitter"
  55636. * @returns a string containing the class name
  55637. */
  55638. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  55639. return "SphereDirectedParticleEmitter";
  55640. };
  55641. /**
  55642. * Serializes the particle system to a JSON object.
  55643. * @returns the JSON object
  55644. */
  55645. SphereDirectedParticleEmitter.prototype.serialize = function () {
  55646. var serializationObject = _super.prototype.serialize.call(this);
  55647. ;
  55648. serializationObject.direction1 = this.direction1.asArray();
  55649. ;
  55650. serializationObject.direction2 = this.direction2.asArray();
  55651. ;
  55652. return serializationObject;
  55653. };
  55654. /**
  55655. * Parse properties from a JSON object
  55656. * @param serializationObject defines the JSON object
  55657. */
  55658. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  55659. _super.prototype.parse.call(this, serializationObject);
  55660. this.direction1.copyFrom(serializationObject.direction1);
  55661. this.direction2.copyFrom(serializationObject.direction2);
  55662. };
  55663. return SphereDirectedParticleEmitter;
  55664. }(SphereParticleEmitter));
  55665. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  55666. })(BABYLON || (BABYLON = {}));
  55667. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  55668. "use strict";
  55669. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55670. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55671. s = arguments[i];
  55672. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55673. t[p] = s[p];
  55674. }
  55675. return t;
  55676. };
  55677. var BABYLON;
  55678. (function (BABYLON) {
  55679. /**
  55680. * This represents a GPU particle system in Babylon
  55681. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  55682. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  55683. */
  55684. var GPUParticleSystem = /** @class */ (function () {
  55685. /**
  55686. * Instantiates a GPU particle system.
  55687. * 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.
  55688. * @param name The name of the particle system
  55689. * @param capacity The max number of particles alive at the same time
  55690. * @param scene The scene the particle system belongs to
  55691. */
  55692. function GPUParticleSystem(name, options, scene) {
  55693. /**
  55694. * The emitter represents the Mesh or position we are attaching the particle system to.
  55695. */
  55696. this.emitter = null;
  55697. /**
  55698. * The rendering group used by the Particle system to chose when to render.
  55699. */
  55700. this.renderingGroupId = 0;
  55701. /**
  55702. * The layer mask we are rendering the particles through.
  55703. */
  55704. this.layerMask = 0x0FFFFFFF;
  55705. this._targetIndex = 0;
  55706. this._currentRenderId = -1;
  55707. this._started = false;
  55708. this._stopped = false;
  55709. this._timeDelta = 0;
  55710. this._attributesStrideSize = 14;
  55711. this._actualFrame = 0;
  55712. /**
  55713. * List of animations used by the particle system.
  55714. */
  55715. this.animations = [];
  55716. /**
  55717. * An event triggered when the system is disposed.
  55718. */
  55719. this.onDisposeObservable = new BABYLON.Observable();
  55720. /**
  55721. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55722. */
  55723. this.updateSpeed = 0.01;
  55724. /**
  55725. * The amount of time the particle system is running (depends of the overall update speed).
  55726. */
  55727. this.targetStopDuration = 0;
  55728. /**
  55729. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55730. */
  55731. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55732. /**
  55733. * Minimum life time of emitting particles.
  55734. */
  55735. this.minLifeTime = 1;
  55736. /**
  55737. * Maximum life time of emitting particles.
  55738. */
  55739. this.maxLifeTime = 1;
  55740. /**
  55741. * Minimum Size of emitting particles.
  55742. */
  55743. this.minSize = 1;
  55744. /**
  55745. * Maximum Size of emitting particles.
  55746. */
  55747. this.maxSize = 1;
  55748. /**
  55749. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55750. */
  55751. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55752. /**
  55753. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55754. */
  55755. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55756. /**
  55757. * Color the particle will have at the end of its lifetime.
  55758. */
  55759. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  55760. /**
  55761. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  55762. */
  55763. this.emitRate = 100;
  55764. /**
  55765. * You can use gravity if you want to give an orientation to your particles.
  55766. */
  55767. this.gravity = BABYLON.Vector3.Zero();
  55768. /**
  55769. * Minimum power of emitting particles.
  55770. */
  55771. this.minEmitPower = 1;
  55772. /**
  55773. * Maximum power of emitting particles.
  55774. */
  55775. this.maxEmitPower = 1;
  55776. /**
  55777. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55778. * to override the particles.
  55779. */
  55780. this.forceDepthWrite = false;
  55781. this.id = name;
  55782. this.name = name;
  55783. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55784. this._engine = this._scene.getEngine();
  55785. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  55786. this._capacity = fullOptions.capacity;
  55787. this._activeCount = fullOptions.capacity;
  55788. this._currentActiveCount = 0;
  55789. this._scene.particleSystems.push(this);
  55790. this._updateEffectOptions = {
  55791. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  55792. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  55793. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  55794. uniformBuffersNames: [],
  55795. samplers: ["randomSampler"],
  55796. defines: "",
  55797. fallbacks: null,
  55798. onCompiled: null,
  55799. onError: null,
  55800. indexParameters: null,
  55801. maxSimultaneousLights: 0,
  55802. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  55803. };
  55804. // Random data
  55805. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  55806. var d = [];
  55807. for (var i = 0; i < maxTextureSize; ++i) {
  55808. d.push(Math.random());
  55809. d.push(Math.random());
  55810. d.push(Math.random());
  55811. d.push(Math.random());
  55812. }
  55813. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  55814. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55815. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55816. this._randomTextureSize = maxTextureSize;
  55817. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55818. }
  55819. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  55820. /**
  55821. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  55822. */
  55823. get: function () {
  55824. if (!BABYLON.Engine.LastCreatedEngine) {
  55825. return false;
  55826. }
  55827. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  55828. },
  55829. enumerable: true,
  55830. configurable: true
  55831. });
  55832. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  55833. /**
  55834. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55835. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55836. */
  55837. get: function () {
  55838. if (this.particleEmitterType.direction1) {
  55839. return this.particleEmitterType.direction1;
  55840. }
  55841. return BABYLON.Vector3.Zero();
  55842. },
  55843. set: function (value) {
  55844. if (this.particleEmitterType.direction1) {
  55845. this.particleEmitterType.direction1 = value;
  55846. }
  55847. },
  55848. enumerable: true,
  55849. configurable: true
  55850. });
  55851. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  55852. /**
  55853. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55854. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55855. */
  55856. get: function () {
  55857. if (this.particleEmitterType.direction2) {
  55858. return this.particleEmitterType.direction2;
  55859. }
  55860. return BABYLON.Vector3.Zero();
  55861. },
  55862. set: function (value) {
  55863. if (this.particleEmitterType.direction2) {
  55864. this.particleEmitterType.direction2 = value;
  55865. }
  55866. },
  55867. enumerable: true,
  55868. configurable: true
  55869. });
  55870. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  55871. /**
  55872. * 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.
  55873. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55874. */
  55875. get: function () {
  55876. if (this.particleEmitterType.minEmitBox) {
  55877. return this.particleEmitterType.minEmitBox;
  55878. }
  55879. return BABYLON.Vector3.Zero();
  55880. },
  55881. set: function (value) {
  55882. if (this.particleEmitterType.minEmitBox) {
  55883. this.particleEmitterType.minEmitBox = value;
  55884. }
  55885. },
  55886. enumerable: true,
  55887. configurable: true
  55888. });
  55889. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  55890. /**
  55891. * 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.
  55892. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55893. */
  55894. get: function () {
  55895. if (this.particleEmitterType.maxEmitBox) {
  55896. return this.particleEmitterType.maxEmitBox;
  55897. }
  55898. return BABYLON.Vector3.Zero();
  55899. },
  55900. set: function (value) {
  55901. if (this.particleEmitterType.maxEmitBox) {
  55902. this.particleEmitterType.maxEmitBox = value;
  55903. }
  55904. },
  55905. enumerable: true,
  55906. configurable: true
  55907. });
  55908. /**
  55909. * Gets the maximum number of particles active at the same time.
  55910. * @returns The max number of active particles.
  55911. */
  55912. GPUParticleSystem.prototype.getCapacity = function () {
  55913. return this._capacity;
  55914. };
  55915. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  55916. /**
  55917. * Gets or set the number of active particles
  55918. */
  55919. get: function () {
  55920. return this._activeCount;
  55921. },
  55922. set: function (value) {
  55923. this._activeCount = Math.min(value, this._capacity);
  55924. },
  55925. enumerable: true,
  55926. configurable: true
  55927. });
  55928. /**
  55929. * Is this system ready to be used/rendered
  55930. * @return true if the system is ready
  55931. */
  55932. GPUParticleSystem.prototype.isReady = function () {
  55933. if (!this._updateEffect) {
  55934. this._recreateUpdateEffect();
  55935. this._recreateRenderEffect();
  55936. return false;
  55937. }
  55938. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55939. return false;
  55940. }
  55941. return true;
  55942. };
  55943. /**
  55944. * Gets Wether the system has been started.
  55945. * @returns True if it has been started, otherwise false.
  55946. */
  55947. GPUParticleSystem.prototype.isStarted = function () {
  55948. return this._started;
  55949. };
  55950. /**
  55951. * Starts the particle system and begins to emit.
  55952. */
  55953. GPUParticleSystem.prototype.start = function () {
  55954. this._started = true;
  55955. this._stopped = false;
  55956. };
  55957. /**
  55958. * Stops the particle system.
  55959. */
  55960. GPUParticleSystem.prototype.stop = function () {
  55961. this._stopped = true;
  55962. };
  55963. /**
  55964. * Remove all active particles
  55965. */
  55966. GPUParticleSystem.prototype.reset = function () {
  55967. this._releaseBuffers();
  55968. this._releaseVAOs();
  55969. this._currentActiveCount = 0;
  55970. this._targetIndex = 0;
  55971. };
  55972. /**
  55973. * Returns the string "GPUParticleSystem"
  55974. * @returns a string containing the class name
  55975. */
  55976. GPUParticleSystem.prototype.getClassName = function () {
  55977. return "GPUParticleSystem";
  55978. };
  55979. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  55980. var updateVertexBuffers = {};
  55981. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  55982. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  55983. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  55984. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  55985. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  55986. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  55987. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  55988. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  55989. this._engine.bindArrayBuffer(null);
  55990. return vao;
  55991. };
  55992. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  55993. var renderVertexBuffers = {};
  55994. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  55995. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  55996. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  55997. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  55998. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  55999. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56000. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56001. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56002. this._engine.bindArrayBuffer(null);
  56003. return vao;
  56004. };
  56005. GPUParticleSystem.prototype._initialize = function (force) {
  56006. if (force === void 0) { force = false; }
  56007. if (this._buffer0 && !force) {
  56008. return;
  56009. }
  56010. var engine = this._scene.getEngine();
  56011. var data = new Array();
  56012. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56013. // position
  56014. data.push(0.0);
  56015. data.push(0.0);
  56016. data.push(0.0);
  56017. // Age and life
  56018. data.push(0.0); // create the particle as a dead one to create a new one at start
  56019. data.push(0.0);
  56020. // Seed
  56021. data.push(Math.random());
  56022. // Size
  56023. data.push(0.0);
  56024. // color
  56025. data.push(0.0);
  56026. data.push(0.0);
  56027. data.push(0.0);
  56028. data.push(0.0);
  56029. // direction
  56030. data.push(0.0);
  56031. data.push(0.0);
  56032. data.push(0.0);
  56033. }
  56034. // Sprite data
  56035. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56036. -0.5, 0.5, 0, 1,
  56037. -0.5, -0.5, 0, 0,
  56038. 0.5, -0.5, 1, 0]);
  56039. // Buffers
  56040. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56041. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56042. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56043. // Update VAO
  56044. this._updateVAO = [];
  56045. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56046. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56047. // Render VAO
  56048. this._renderVAO = [];
  56049. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56050. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56051. // Links
  56052. this._sourceBuffer = this._buffer0;
  56053. this._targetBuffer = this._buffer1;
  56054. };
  56055. /** @ignore */
  56056. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56057. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56058. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  56059. return;
  56060. }
  56061. this._updateEffectOptions.defines = defines;
  56062. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  56063. };
  56064. /** @ignore */
  56065. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  56066. var defines = "";
  56067. if (this._scene.clipPlane) {
  56068. defines = "\n#define CLIPPLANE";
  56069. }
  56070. if (this._renderEffect && this._renderEffect.defines === defines) {
  56071. return;
  56072. }
  56073. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  56074. };
  56075. /**
  56076. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56077. */
  56078. GPUParticleSystem.prototype.animate = function () {
  56079. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  56080. this._actualFrame += this._timeDelta;
  56081. if (!this._stopped) {
  56082. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  56083. this.stop();
  56084. }
  56085. }
  56086. };
  56087. /**
  56088. * Renders the particle system in its current state.
  56089. * @returns the current number of particles
  56090. */
  56091. GPUParticleSystem.prototype.render = function () {
  56092. if (!this._started) {
  56093. return 0;
  56094. }
  56095. this._recreateUpdateEffect();
  56096. this._recreateRenderEffect();
  56097. if (!this.isReady()) {
  56098. return 0;
  56099. }
  56100. if (this._currentRenderId === this._scene.getRenderId()) {
  56101. return 0;
  56102. }
  56103. this._currentRenderId = this._scene.getRenderId();
  56104. // Get everything ready to render
  56105. this._initialize();
  56106. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  56107. // Enable update effect
  56108. this._engine.enableEffect(this._updateEffect);
  56109. this._engine.setState(false);
  56110. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  56111. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  56112. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  56113. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  56114. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  56115. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  56116. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  56117. this._updateEffect.setDirectColor4("color1", this.color1);
  56118. this._updateEffect.setDirectColor4("color2", this.color2);
  56119. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  56120. this._updateEffect.setVector3("gravity", this.gravity);
  56121. if (this.particleEmitterType) {
  56122. this.particleEmitterType.applyToShader(this._updateEffect);
  56123. }
  56124. var emitterWM;
  56125. if (this.emitter.position) {
  56126. var emitterMesh = this.emitter;
  56127. emitterWM = emitterMesh.getWorldMatrix();
  56128. }
  56129. else {
  56130. var emitterPosition = this.emitter;
  56131. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56132. }
  56133. this._updateEffect.setMatrix("emitterWM", emitterWM);
  56134. // Bind source VAO
  56135. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  56136. // Update
  56137. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  56138. this._engine.setRasterizerState(false);
  56139. this._engine.beginTransformFeedback();
  56140. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  56141. this._engine.endTransformFeedback();
  56142. this._engine.setRasterizerState(true);
  56143. this._engine.bindTransformFeedbackBuffer(null);
  56144. // Enable render effect
  56145. this._engine.enableEffect(this._renderEffect);
  56146. var viewMatrix = this._scene.getViewMatrix();
  56147. this._renderEffect.setMatrix("view", viewMatrix);
  56148. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  56149. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  56150. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  56151. if (this._scene.clipPlane) {
  56152. var clipPlane = this._scene.clipPlane;
  56153. var invView = viewMatrix.clone();
  56154. invView.invert();
  56155. this._renderEffect.setMatrix("invView", invView);
  56156. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56157. }
  56158. // Draw order
  56159. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  56160. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56161. }
  56162. else {
  56163. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56164. }
  56165. if (this.forceDepthWrite) {
  56166. this._engine.setDepthWrite(true);
  56167. }
  56168. // Bind source VAO
  56169. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  56170. // Render
  56171. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  56172. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56173. // Switch VAOs
  56174. this._targetIndex++;
  56175. if (this._targetIndex === 2) {
  56176. this._targetIndex = 0;
  56177. }
  56178. // Switch buffers
  56179. var tmpBuffer = this._sourceBuffer;
  56180. this._sourceBuffer = this._targetBuffer;
  56181. this._targetBuffer = tmpBuffer;
  56182. return this._currentActiveCount;
  56183. };
  56184. /**
  56185. * Rebuilds the particle system
  56186. */
  56187. GPUParticleSystem.prototype.rebuild = function () {
  56188. this._initialize(true);
  56189. };
  56190. GPUParticleSystem.prototype._releaseBuffers = function () {
  56191. if (this._buffer0) {
  56192. this._buffer0.dispose();
  56193. this._buffer0 = null;
  56194. }
  56195. if (this._buffer1) {
  56196. this._buffer1.dispose();
  56197. this._buffer1 = null;
  56198. }
  56199. if (this._spriteBuffer) {
  56200. this._spriteBuffer.dispose();
  56201. this._spriteBuffer = null;
  56202. }
  56203. };
  56204. GPUParticleSystem.prototype._releaseVAOs = function () {
  56205. if (!this._updateVAO) {
  56206. return;
  56207. }
  56208. for (var index = 0; index < this._updateVAO.length; index++) {
  56209. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  56210. }
  56211. this._updateVAO = [];
  56212. for (var index = 0; index < this._renderVAO.length; index++) {
  56213. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  56214. }
  56215. this._renderVAO = [];
  56216. };
  56217. /**
  56218. * Disposes the particle system and free the associated resources
  56219. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56220. */
  56221. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  56222. if (disposeTexture === void 0) { disposeTexture = true; }
  56223. var index = this._scene.particleSystems.indexOf(this);
  56224. if (index > -1) {
  56225. this._scene.particleSystems.splice(index, 1);
  56226. }
  56227. this._releaseBuffers();
  56228. this._releaseVAOs();
  56229. if (this._randomTexture) {
  56230. this._randomTexture.dispose();
  56231. this._randomTexture = null;
  56232. }
  56233. if (disposeTexture && this.particleTexture) {
  56234. this.particleTexture.dispose();
  56235. this.particleTexture = null;
  56236. }
  56237. // Callback
  56238. this.onDisposeObservable.notifyObservers(this);
  56239. this.onDisposeObservable.clear();
  56240. };
  56241. /**
  56242. * Clones the particle system.
  56243. * @param name The name of the cloned object
  56244. * @param newEmitter The new emitter to use
  56245. * @returns the cloned particle system
  56246. */
  56247. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  56248. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  56249. BABYLON.Tools.DeepCopy(this, result);
  56250. if (newEmitter === undefined) {
  56251. newEmitter = this.emitter;
  56252. }
  56253. result.emitter = newEmitter;
  56254. if (this.particleTexture) {
  56255. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56256. }
  56257. return result;
  56258. };
  56259. /**
  56260. * Serializes the particle system to a JSON object.
  56261. * @returns the JSON object
  56262. */
  56263. GPUParticleSystem.prototype.serialize = function () {
  56264. var serializationObject = {};
  56265. serializationObject.name = this.name;
  56266. serializationObject.id = this.id;
  56267. // Emitter
  56268. if (this.emitter.position) {
  56269. var emitterMesh = this.emitter;
  56270. serializationObject.emitterId = emitterMesh.id;
  56271. }
  56272. else {
  56273. var emitterPosition = this.emitter;
  56274. serializationObject.emitter = emitterPosition.asArray();
  56275. }
  56276. serializationObject.capacity = this.getCapacity();
  56277. if (this.particleTexture) {
  56278. serializationObject.textureName = this.particleTexture.name;
  56279. }
  56280. // Animations
  56281. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56282. // Particle system
  56283. serializationObject.activeParticleCount = this.activeParticleCount;
  56284. serializationObject.randomTextureSize = this._randomTextureSize;
  56285. serializationObject.minSize = this.minSize;
  56286. serializationObject.maxSize = this.maxSize;
  56287. serializationObject.minEmitPower = this.minEmitPower;
  56288. serializationObject.maxEmitPower = this.maxEmitPower;
  56289. serializationObject.minLifeTime = this.minLifeTime;
  56290. serializationObject.maxLifeTime = this.maxLifeTime;
  56291. serializationObject.emitRate = this.emitRate;
  56292. serializationObject.gravity = this.gravity.asArray();
  56293. serializationObject.color1 = this.color1.asArray();
  56294. serializationObject.color2 = this.color2.asArray();
  56295. serializationObject.colorDead = this.colorDead.asArray();
  56296. serializationObject.updateSpeed = this.updateSpeed;
  56297. serializationObject.targetStopDuration = this.targetStopDuration;
  56298. serializationObject.blendMode = this.blendMode;
  56299. // Emitter
  56300. if (this.particleEmitterType) {
  56301. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56302. }
  56303. return serializationObject;
  56304. };
  56305. /**
  56306. * Parses a JSON object to create a GPU particle system.
  56307. * @param parsedParticleSystem The JSON object to parse
  56308. * @param scene The scene to create the particle system in
  56309. * @param rootUrl The root url to use to load external dependencies like texture
  56310. * @returns the parsed GPU particle system
  56311. */
  56312. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56313. var name = parsedParticleSystem.name;
  56314. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  56315. if (parsedParticleSystem.id) {
  56316. particleSystem.id = parsedParticleSystem.id;
  56317. }
  56318. // Texture
  56319. if (parsedParticleSystem.textureName) {
  56320. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56321. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56322. }
  56323. // Emitter
  56324. if (parsedParticleSystem.emitterId) {
  56325. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56326. }
  56327. else {
  56328. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56329. }
  56330. // Animations
  56331. if (parsedParticleSystem.animations) {
  56332. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56333. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56334. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56335. }
  56336. }
  56337. // Particle system
  56338. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  56339. particleSystem.minSize = parsedParticleSystem.minSize;
  56340. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56341. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56342. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56343. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56344. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56345. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56346. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56347. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56348. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56349. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56350. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56351. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56352. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56353. // Emitter
  56354. if (parsedParticleSystem.particleEmitterType) {
  56355. var emitterType = void 0;
  56356. switch (parsedParticleSystem.particleEmitterType.type) {
  56357. case "SphereEmitter":
  56358. emitterType = new BABYLON.SphereParticleEmitter();
  56359. break;
  56360. case "SphereDirectedParticleEmitter":
  56361. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56362. break;
  56363. case "ConeEmitter":
  56364. emitterType = new BABYLON.ConeParticleEmitter();
  56365. break;
  56366. case "BoxEmitter":
  56367. default:
  56368. emitterType = new BABYLON.BoxParticleEmitter();
  56369. break;
  56370. }
  56371. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56372. particleSystem.particleEmitterType = emitterType;
  56373. }
  56374. return particleSystem;
  56375. };
  56376. return GPUParticleSystem;
  56377. }());
  56378. BABYLON.GPUParticleSystem = GPUParticleSystem;
  56379. })(BABYLON || (BABYLON = {}));
  56380. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  56381. "use strict";
  56382. var BABYLON;
  56383. (function (BABYLON) {
  56384. /**
  56385. * Represents one particle of a solid particle system.
  56386. */
  56387. var SolidParticle = /** @class */ (function () {
  56388. /**
  56389. * Creates a Solid Particle object.
  56390. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  56391. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  56392. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  56393. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  56394. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  56395. * @param shapeId (integer) is the model shape identifier in the SPS.
  56396. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  56397. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  56398. */
  56399. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  56400. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  56401. /**
  56402. * particle global index
  56403. */
  56404. this.idx = 0;
  56405. /**
  56406. * The color of the particle
  56407. */
  56408. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56409. /**
  56410. * The world space position of the particle.
  56411. */
  56412. this.position = BABYLON.Vector3.Zero();
  56413. /**
  56414. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  56415. */
  56416. this.rotation = BABYLON.Vector3.Zero();
  56417. /**
  56418. * The scaling of the particle.
  56419. */
  56420. this.scaling = BABYLON.Vector3.One();
  56421. /**
  56422. * The uvs of the particle.
  56423. */
  56424. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  56425. /**
  56426. * The current speed of the particle.
  56427. */
  56428. this.velocity = BABYLON.Vector3.Zero();
  56429. /**
  56430. * The pivot point in the particle local space.
  56431. */
  56432. this.pivot = BABYLON.Vector3.Zero();
  56433. /**
  56434. * Must the particle be translated from its pivot point in its local space ?
  56435. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  56436. * Default : false
  56437. */
  56438. this.translateFromPivot = false;
  56439. /**
  56440. * Is the particle active or not ?
  56441. */
  56442. this.alive = true;
  56443. /**
  56444. * Is the particle visible or not ?
  56445. */
  56446. this.isVisible = true;
  56447. /**
  56448. * Index of this particle in the global "positions" array (Internal use)
  56449. */
  56450. this._pos = 0;
  56451. /**
  56452. * Index of this particle in the global "indices" array (Internal use)
  56453. */
  56454. this._ind = 0;
  56455. /**
  56456. * ModelShape id of this particle
  56457. */
  56458. this.shapeId = 0;
  56459. /**
  56460. * Index of the particle in its shape id (Internal use)
  56461. */
  56462. this.idxInShape = 0;
  56463. /**
  56464. * Still set as invisible in order to skip useless computations (Internal use)
  56465. */
  56466. this._stillInvisible = false;
  56467. /**
  56468. * Last computed particle rotation matrix
  56469. */
  56470. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  56471. /**
  56472. * Parent particle Id, if any.
  56473. * Default null.
  56474. */
  56475. this.parentId = null;
  56476. /**
  56477. * Internal global position in the SPS.
  56478. */
  56479. this._globalPosition = BABYLON.Vector3.Zero();
  56480. this.idx = particleIndex;
  56481. this._pos = positionIndex;
  56482. this._ind = indiceIndex;
  56483. this._model = model;
  56484. this.shapeId = shapeId;
  56485. this.idxInShape = idxInShape;
  56486. this._sps = sps;
  56487. if (modelBoundingInfo) {
  56488. this._modelBoundingInfo = modelBoundingInfo;
  56489. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  56490. }
  56491. }
  56492. Object.defineProperty(SolidParticle.prototype, "scale", {
  56493. /**
  56494. * Legacy support, changed scale to scaling
  56495. */
  56496. get: function () {
  56497. return this.scaling;
  56498. },
  56499. /**
  56500. * Legacy support, changed scale to scaling
  56501. */
  56502. set: function (scale) {
  56503. this.scaling = scale;
  56504. },
  56505. enumerable: true,
  56506. configurable: true
  56507. });
  56508. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56509. /**
  56510. * Legacy support, changed quaternion to rotationQuaternion
  56511. */
  56512. get: function () {
  56513. return this.rotationQuaternion;
  56514. },
  56515. /**
  56516. * Legacy support, changed quaternion to rotationQuaternion
  56517. */
  56518. set: function (q) {
  56519. this.rotationQuaternion = q;
  56520. },
  56521. enumerable: true,
  56522. configurable: true
  56523. });
  56524. /**
  56525. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  56526. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  56527. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  56528. * @returns true if it intersects
  56529. */
  56530. SolidParticle.prototype.intersectsMesh = function (target) {
  56531. if (!this._boundingInfo || !target._boundingInfo) {
  56532. return false;
  56533. }
  56534. if (this._sps._bSphereOnly) {
  56535. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  56536. }
  56537. return this._boundingInfo.intersects(target._boundingInfo, false);
  56538. };
  56539. return SolidParticle;
  56540. }());
  56541. BABYLON.SolidParticle = SolidParticle;
  56542. /**
  56543. * Represents the shape of the model used by one particle of a solid particle system.
  56544. * SPS internal tool, don't use it manually.
  56545. */
  56546. var ModelShape = /** @class */ (function () {
  56547. /**
  56548. * 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.
  56549. * SPS internal tool, don't use it manually.
  56550. * @ignore
  56551. */
  56552. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  56553. /**
  56554. * length of the shape in the model indices array (internal use)
  56555. */
  56556. this._indicesLength = 0;
  56557. this.shapeID = id;
  56558. this._shape = shape;
  56559. this._indicesLength = indicesLength;
  56560. this._shapeUV = shapeUV;
  56561. this._positionFunction = posFunction;
  56562. this._vertexFunction = vtxFunction;
  56563. }
  56564. return ModelShape;
  56565. }());
  56566. BABYLON.ModelShape = ModelShape;
  56567. /**
  56568. * Represents a Depth Sorted Particle in the solid particle system.
  56569. */
  56570. var DepthSortedParticle = /** @class */ (function () {
  56571. function DepthSortedParticle() {
  56572. /**
  56573. * Index of the particle in the "indices" array
  56574. */
  56575. this.ind = 0;
  56576. /**
  56577. * Length of the particle shape in the "indices" array
  56578. */
  56579. this.indicesLength = 0;
  56580. /**
  56581. * Squared distance from the particle to the camera
  56582. */
  56583. this.sqDistance = 0.0;
  56584. }
  56585. return DepthSortedParticle;
  56586. }());
  56587. BABYLON.DepthSortedParticle = DepthSortedParticle;
  56588. })(BABYLON || (BABYLON = {}));
  56589. //# sourceMappingURL=babylon.solidParticle.js.map
  56590. "use strict";
  56591. var BABYLON;
  56592. (function (BABYLON) {
  56593. /**
  56594. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  56595. *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.
  56596. * The SPS is also a particle system. It provides some methods to manage the particles.
  56597. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  56598. *
  56599. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  56600. */
  56601. var SolidParticleSystem = /** @class */ (function () {
  56602. /**
  56603. * Creates a SPS (Solid Particle System) object.
  56604. * @param name (String) is the SPS name, this will be the underlying mesh name.
  56605. * @param scene (Scene) is the scene in which the SPS is added.
  56606. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  56607. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  56608. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  56609. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  56610. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  56611. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  56612. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  56613. */
  56614. function SolidParticleSystem(name, scene, options) {
  56615. /**
  56616. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  56617. * Example : var p = SPS.particles[i];
  56618. */
  56619. this.particles = new Array();
  56620. /**
  56621. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  56622. */
  56623. this.nbParticles = 0;
  56624. /**
  56625. * If the particles must ever face the camera (default false). Useful for planar particles.
  56626. */
  56627. this.billboard = false;
  56628. /**
  56629. * Recompute normals when adding a shape
  56630. */
  56631. this.recomputeNormals = true;
  56632. /**
  56633. * This a counter ofr your own usage. It's not set by any SPS functions.
  56634. */
  56635. this.counter = 0;
  56636. /**
  56637. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  56638. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  56639. */
  56640. this.vars = {};
  56641. /**
  56642. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  56643. */
  56644. this._bSphereOnly = false;
  56645. /**
  56646. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  56647. */
  56648. this._bSphereRadiusFactor = 1.0;
  56649. this._positions = new Array();
  56650. this._indices = new Array();
  56651. this._normals = new Array();
  56652. this._colors = new Array();
  56653. this._uvs = new Array();
  56654. this._index = 0; // indices index
  56655. this._updatable = true;
  56656. this._pickable = false;
  56657. this._isVisibilityBoxLocked = false;
  56658. this._alwaysVisible = false;
  56659. this._depthSort = false;
  56660. this._shapeCounter = 0;
  56661. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  56662. this._color = new BABYLON.Color4(0, 0, 0, 0);
  56663. this._computeParticleColor = true;
  56664. this._computeParticleTexture = true;
  56665. this._computeParticleRotation = true;
  56666. this._computeParticleVertex = false;
  56667. this._computeBoundingBox = false;
  56668. this._depthSortParticles = true;
  56669. this._cam_axisZ = BABYLON.Vector3.Zero();
  56670. this._cam_axisY = BABYLON.Vector3.Zero();
  56671. this._cam_axisX = BABYLON.Vector3.Zero();
  56672. this._axisZ = BABYLON.Axis.Z;
  56673. this._camDir = BABYLON.Vector3.Zero();
  56674. this._camInvertedPosition = BABYLON.Vector3.Zero();
  56675. this._rotMatrix = new BABYLON.Matrix();
  56676. this._invertMatrix = new BABYLON.Matrix();
  56677. this._rotated = BABYLON.Vector3.Zero();
  56678. this._quaternion = new BABYLON.Quaternion();
  56679. this._vertex = BABYLON.Vector3.Zero();
  56680. this._normal = BABYLON.Vector3.Zero();
  56681. this._yaw = 0.0;
  56682. this._pitch = 0.0;
  56683. this._roll = 0.0;
  56684. this._halfroll = 0.0;
  56685. this._halfpitch = 0.0;
  56686. this._halfyaw = 0.0;
  56687. this._sinRoll = 0.0;
  56688. this._cosRoll = 0.0;
  56689. this._sinPitch = 0.0;
  56690. this._cosPitch = 0.0;
  56691. this._sinYaw = 0.0;
  56692. this._cosYaw = 0.0;
  56693. this._mustUnrotateFixedNormals = false;
  56694. this._minimum = BABYLON.Vector3.Zero();
  56695. this._maximum = BABYLON.Vector3.Zero();
  56696. this._minBbox = BABYLON.Vector3.Zero();
  56697. this._maxBbox = BABYLON.Vector3.Zero();
  56698. this._particlesIntersect = false;
  56699. this._depthSortFunction = function (p1, p2) {
  56700. return (p2.sqDistance - p1.sqDistance);
  56701. };
  56702. this._needs32Bits = false;
  56703. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  56704. this._scaledPivot = BABYLON.Vector3.Zero();
  56705. this._particleHasParent = false;
  56706. this.name = name;
  56707. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56708. this._camera = scene.activeCamera;
  56709. this._pickable = options ? options.isPickable : false;
  56710. this._depthSort = options ? options.enableDepthSort : false;
  56711. this._particlesIntersect = options ? options.particleIntersection : false;
  56712. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  56713. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  56714. if (options && options.updatable) {
  56715. this._updatable = options.updatable;
  56716. }
  56717. else {
  56718. this._updatable = true;
  56719. }
  56720. if (this._pickable) {
  56721. this.pickedParticles = [];
  56722. }
  56723. if (this._depthSort) {
  56724. this.depthSortedParticles = [];
  56725. }
  56726. }
  56727. /**
  56728. * Builds the SPS underlying mesh. Returns a standard Mesh.
  56729. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  56730. * @returns the created mesh
  56731. */
  56732. SolidParticleSystem.prototype.buildMesh = function () {
  56733. if (this.nbParticles === 0) {
  56734. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  56735. this.addShape(triangle, 1);
  56736. triangle.dispose();
  56737. }
  56738. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  56739. this._positions32 = new Float32Array(this._positions);
  56740. this._uvs32 = new Float32Array(this._uvs);
  56741. this._colors32 = new Float32Array(this._colors);
  56742. if (this.recomputeNormals) {
  56743. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  56744. }
  56745. this._normals32 = new Float32Array(this._normals);
  56746. this._fixedNormal32 = new Float32Array(this._normals);
  56747. if (this._mustUnrotateFixedNormals) {
  56748. this._unrotateFixedNormals();
  56749. }
  56750. var vertexData = new BABYLON.VertexData();
  56751. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  56752. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  56753. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  56754. if (this._uvs32) {
  56755. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  56756. ;
  56757. }
  56758. if (this._colors32) {
  56759. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  56760. }
  56761. var mesh = new BABYLON.Mesh(this.name, this._scene);
  56762. vertexData.applyToMesh(mesh, this._updatable);
  56763. this.mesh = mesh;
  56764. this.mesh.isPickable = this._pickable;
  56765. // free memory
  56766. if (!this._depthSort) {
  56767. this._indices = null;
  56768. }
  56769. this._positions = null;
  56770. this._normals = null;
  56771. this._uvs = null;
  56772. this._colors = null;
  56773. if (!this._updatable) {
  56774. this.particles.length = 0;
  56775. }
  56776. return mesh;
  56777. };
  56778. /**
  56779. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  56780. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  56781. * Thus the particles generated from `digest()` have their property `position` set yet.
  56782. * @param mesh ( Mesh ) is the mesh to be digested
  56783. * @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
  56784. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  56785. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  56786. * @returns the current SPS
  56787. */
  56788. SolidParticleSystem.prototype.digest = function (mesh, options) {
  56789. var size = (options && options.facetNb) || 1;
  56790. var number = (options && options.number) || 0;
  56791. var delta = (options && options.delta) || 0;
  56792. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56793. var meshInd = mesh.getIndices();
  56794. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56795. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56796. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56797. var f = 0; // facet counter
  56798. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  56799. // compute size from number
  56800. if (number) {
  56801. number = (number > totalFacets) ? totalFacets : number;
  56802. size = Math.round(totalFacets / number);
  56803. delta = 0;
  56804. }
  56805. else {
  56806. size = (size > totalFacets) ? totalFacets : size;
  56807. }
  56808. var facetPos = []; // submesh positions
  56809. var facetInd = []; // submesh indices
  56810. var facetUV = []; // submesh UV
  56811. var facetCol = []; // submesh colors
  56812. var barycenter = BABYLON.Vector3.Zero();
  56813. var sizeO = size;
  56814. while (f < totalFacets) {
  56815. size = sizeO + Math.floor((1 + delta) * Math.random());
  56816. if (f > totalFacets - size) {
  56817. size = totalFacets - f;
  56818. }
  56819. // reset temp arrays
  56820. facetPos.length = 0;
  56821. facetInd.length = 0;
  56822. facetUV.length = 0;
  56823. facetCol.length = 0;
  56824. // iterate over "size" facets
  56825. var fi = 0;
  56826. for (var j = f * 3; j < (f + size) * 3; j++) {
  56827. facetInd.push(fi);
  56828. var i = meshInd[j];
  56829. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  56830. if (meshUV) {
  56831. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  56832. }
  56833. if (meshCol) {
  56834. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  56835. }
  56836. fi++;
  56837. }
  56838. // create a model shape for each single particle
  56839. var idx = this.nbParticles;
  56840. var shape = this._posToShape(facetPos);
  56841. var shapeUV = this._uvsToShapeUV(facetUV);
  56842. // compute the barycenter of the shape
  56843. var v;
  56844. for (v = 0; v < shape.length; v++) {
  56845. barycenter.addInPlace(shape[v]);
  56846. }
  56847. barycenter.scaleInPlace(1 / shape.length);
  56848. // shift the shape from its barycenter to the origin
  56849. for (v = 0; v < shape.length; v++) {
  56850. shape[v].subtractInPlace(barycenter);
  56851. }
  56852. var bInfo;
  56853. if (this._particlesIntersect) {
  56854. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  56855. }
  56856. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  56857. // add the particle in the SPS
  56858. var currentPos = this._positions.length;
  56859. var currentInd = this._indices.length;
  56860. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  56861. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  56862. // initialize the particle position
  56863. this.particles[this.nbParticles].position.addInPlace(barycenter);
  56864. this._index += shape.length;
  56865. idx++;
  56866. this.nbParticles++;
  56867. this._shapeCounter++;
  56868. f += size;
  56869. }
  56870. return this;
  56871. };
  56872. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  56873. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  56874. var index = 0;
  56875. var idx = 0;
  56876. for (var p = 0; p < this.particles.length; p++) {
  56877. this._particle = this.particles[p];
  56878. this._shape = this._particle._model._shape;
  56879. if (this._particle.rotationQuaternion) {
  56880. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  56881. }
  56882. else {
  56883. this._yaw = this._particle.rotation.y;
  56884. this._pitch = this._particle.rotation.x;
  56885. this._roll = this._particle.rotation.z;
  56886. this._quaternionRotationYPR();
  56887. }
  56888. this._quaternionToRotationMatrix();
  56889. this._rotMatrix.invertToRef(this._invertMatrix);
  56890. for (var pt = 0; pt < this._shape.length; pt++) {
  56891. idx = index + pt * 3;
  56892. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  56893. this._fixedNormal32[idx] = this._normal.x;
  56894. this._fixedNormal32[idx + 1] = this._normal.y;
  56895. this._fixedNormal32[idx + 2] = this._normal.z;
  56896. }
  56897. index = idx + 3;
  56898. }
  56899. };
  56900. //reset copy
  56901. SolidParticleSystem.prototype._resetCopy = function () {
  56902. this._copy.position.x = 0;
  56903. this._copy.position.y = 0;
  56904. this._copy.position.z = 0;
  56905. this._copy.rotation.x = 0;
  56906. this._copy.rotation.y = 0;
  56907. this._copy.rotation.z = 0;
  56908. this._copy.rotationQuaternion = null;
  56909. this._copy.scaling.x = 1.0;
  56910. this._copy.scaling.y = 1.0;
  56911. this._copy.scaling.z = 1.0;
  56912. this._copy.uvs.x = 0;
  56913. this._copy.uvs.y = 0;
  56914. this._copy.uvs.z = 1.0;
  56915. this._copy.uvs.w = 1.0;
  56916. this._copy.color = null;
  56917. this._copy.translateFromPivot = false;
  56918. };
  56919. // _meshBuilder : inserts the shape model in the global SPS mesh
  56920. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  56921. var i;
  56922. var u = 0;
  56923. var c = 0;
  56924. var n = 0;
  56925. this._resetCopy();
  56926. if (options && options.positionFunction) {
  56927. options.positionFunction(this._copy, idx, idxInShape);
  56928. this._mustUnrotateFixedNormals = true;
  56929. }
  56930. if (this._copy.rotationQuaternion) {
  56931. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56932. }
  56933. else {
  56934. this._yaw = this._copy.rotation.y;
  56935. this._pitch = this._copy.rotation.x;
  56936. this._roll = this._copy.rotation.z;
  56937. this._quaternionRotationYPR();
  56938. }
  56939. this._quaternionToRotationMatrix();
  56940. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  56941. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  56942. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  56943. if (this._copy.translateFromPivot) {
  56944. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  56945. }
  56946. else {
  56947. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  56948. }
  56949. for (i = 0; i < shape.length; i++) {
  56950. this._vertex.x = shape[i].x;
  56951. this._vertex.y = shape[i].y;
  56952. this._vertex.z = shape[i].z;
  56953. if (options && options.vertexFunction) {
  56954. options.vertexFunction(this._copy, this._vertex, i);
  56955. }
  56956. this._vertex.x *= this._copy.scaling.x;
  56957. this._vertex.y *= this._copy.scaling.y;
  56958. this._vertex.z *= this._copy.scaling.z;
  56959. this._vertex.x -= this._scaledPivot.x;
  56960. this._vertex.y -= this._scaledPivot.y;
  56961. this._vertex.z -= this._scaledPivot.z;
  56962. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56963. this._rotated.addInPlace(this._pivotBackTranslation);
  56964. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  56965. if (meshUV) {
  56966. 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);
  56967. u += 2;
  56968. }
  56969. if (this._copy.color) {
  56970. this._color = this._copy.color;
  56971. }
  56972. else if (meshCol && meshCol[c] !== undefined) {
  56973. this._color.r = meshCol[c];
  56974. this._color.g = meshCol[c + 1];
  56975. this._color.b = meshCol[c + 2];
  56976. this._color.a = meshCol[c + 3];
  56977. }
  56978. else {
  56979. this._color.r = 1.0;
  56980. this._color.g = 1.0;
  56981. this._color.b = 1.0;
  56982. this._color.a = 1.0;
  56983. }
  56984. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  56985. c += 4;
  56986. if (!this.recomputeNormals && meshNor) {
  56987. this._normal.x = meshNor[n];
  56988. this._normal.y = meshNor[n + 1];
  56989. this._normal.z = meshNor[n + 2];
  56990. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  56991. normals.push(this._normal.x, this._normal.y, this._normal.z);
  56992. n += 3;
  56993. }
  56994. }
  56995. for (i = 0; i < meshInd.length; i++) {
  56996. var current_ind = p + meshInd[i];
  56997. indices.push(current_ind);
  56998. if (current_ind > 65535) {
  56999. this._needs32Bits = true;
  57000. }
  57001. }
  57002. if (this._pickable) {
  57003. var nbfaces = meshInd.length / 3;
  57004. for (i = 0; i < nbfaces; i++) {
  57005. this.pickedParticles.push({ idx: idx, faceId: i });
  57006. }
  57007. }
  57008. if (this._depthSort) {
  57009. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57010. }
  57011. return this._copy;
  57012. };
  57013. // returns a shape array from positions array
  57014. SolidParticleSystem.prototype._posToShape = function (positions) {
  57015. var shape = [];
  57016. for (var i = 0; i < positions.length; i += 3) {
  57017. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57018. }
  57019. return shape;
  57020. };
  57021. // returns a shapeUV array from a Vector4 uvs
  57022. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57023. var shapeUV = [];
  57024. if (uvs) {
  57025. for (var i = 0; i < uvs.length; i++)
  57026. shapeUV.push(uvs[i]);
  57027. }
  57028. return shapeUV;
  57029. };
  57030. // adds a new particle object in the particles array
  57031. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57032. if (bInfo === void 0) { bInfo = null; }
  57033. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57034. this.particles.push(sp);
  57035. return sp;
  57036. };
  57037. /**
  57038. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57039. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57040. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57041. * @param nb (positive integer) the number of particles to be created from this model
  57042. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57043. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57044. * @returns the number of shapes in the system
  57045. */
  57046. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57047. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57048. var meshInd = mesh.getIndices();
  57049. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57050. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57051. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57052. var bbInfo;
  57053. if (this._particlesIntersect) {
  57054. bbInfo = mesh.getBoundingInfo();
  57055. }
  57056. var shape = this._posToShape(meshPos);
  57057. var shapeUV = this._uvsToShapeUV(meshUV);
  57058. var posfunc = options ? options.positionFunction : null;
  57059. var vtxfunc = options ? options.vertexFunction : null;
  57060. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  57061. // particles
  57062. var sp;
  57063. var currentCopy;
  57064. var idx = this.nbParticles;
  57065. for (var i = 0; i < nb; i++) {
  57066. var currentPos = this._positions.length;
  57067. var currentInd = this._indices.length;
  57068. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57069. if (this._updatable) {
  57070. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  57071. sp.position.copyFrom(currentCopy.position);
  57072. sp.rotation.copyFrom(currentCopy.rotation);
  57073. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  57074. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  57075. }
  57076. if (currentCopy.color && sp.color) {
  57077. sp.color.copyFrom(currentCopy.color);
  57078. }
  57079. sp.scaling.copyFrom(currentCopy.scaling);
  57080. sp.uvs.copyFrom(currentCopy.uvs);
  57081. }
  57082. this._index += shape.length;
  57083. idx++;
  57084. }
  57085. this.nbParticles += nb;
  57086. this._shapeCounter++;
  57087. return this._shapeCounter - 1;
  57088. };
  57089. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57090. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57091. this._resetCopy();
  57092. if (particle._model._positionFunction) {
  57093. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57094. }
  57095. if (this._copy.rotationQuaternion) {
  57096. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57097. }
  57098. else {
  57099. this._yaw = this._copy.rotation.y;
  57100. this._pitch = this._copy.rotation.x;
  57101. this._roll = this._copy.rotation.z;
  57102. this._quaternionRotationYPR();
  57103. }
  57104. this._quaternionToRotationMatrix();
  57105. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57106. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57107. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57108. if (this._copy.translateFromPivot) {
  57109. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57110. }
  57111. else {
  57112. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57113. }
  57114. this._shape = particle._model._shape;
  57115. for (var pt = 0; pt < this._shape.length; pt++) {
  57116. this._vertex.x = this._shape[pt].x;
  57117. this._vertex.y = this._shape[pt].y;
  57118. this._vertex.z = this._shape[pt].z;
  57119. if (particle._model._vertexFunction) {
  57120. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57121. }
  57122. this._vertex.x *= this._copy.scaling.x;
  57123. this._vertex.y *= this._copy.scaling.y;
  57124. this._vertex.z *= this._copy.scaling.z;
  57125. this._vertex.x -= this._scaledPivot.x;
  57126. this._vertex.y -= this._scaledPivot.y;
  57127. this._vertex.z -= this._scaledPivot.z;
  57128. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57129. this._rotated.addInPlace(this._pivotBackTranslation);
  57130. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57131. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57132. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57133. }
  57134. particle.position.x = 0.0;
  57135. particle.position.y = 0.0;
  57136. particle.position.z = 0.0;
  57137. particle.rotation.x = 0.0;
  57138. particle.rotation.y = 0.0;
  57139. particle.rotation.z = 0.0;
  57140. particle.rotationQuaternion = null;
  57141. particle.scaling.x = 1.0;
  57142. particle.scaling.y = 1.0;
  57143. particle.scaling.z = 1.0;
  57144. particle.uvs.x = 0.0;
  57145. particle.uvs.y = 0.0;
  57146. particle.uvs.z = 1.0;
  57147. particle.uvs.w = 1.0;
  57148. particle.pivot.x = 0.0;
  57149. particle.pivot.y = 0.0;
  57150. particle.pivot.z = 0.0;
  57151. particle.translateFromPivot = false;
  57152. particle.parentId = null;
  57153. };
  57154. /**
  57155. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57156. * @returns the SPS.
  57157. */
  57158. SolidParticleSystem.prototype.rebuildMesh = function () {
  57159. for (var p = 0; p < this.particles.length; p++) {
  57160. this._rebuildParticle(this.particles[p]);
  57161. }
  57162. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57163. return this;
  57164. };
  57165. /**
  57166. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57167. * This method calls `updateParticle()` for each particle of the SPS.
  57168. * For an animated SPS, it is usually called within the render loop.
  57169. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57170. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57171. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57172. * @returns the SPS.
  57173. */
  57174. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57175. if (start === void 0) { start = 0; }
  57176. if (end === void 0) { end = this.nbParticles - 1; }
  57177. if (update === void 0) { update = true; }
  57178. if (!this._updatable) {
  57179. return this;
  57180. }
  57181. // custom beforeUpdate
  57182. this.beforeUpdateParticles(start, end, update);
  57183. this._cam_axisX.x = 1.0;
  57184. this._cam_axisX.y = 0.0;
  57185. this._cam_axisX.z = 0.0;
  57186. this._cam_axisY.x = 0.0;
  57187. this._cam_axisY.y = 1.0;
  57188. this._cam_axisY.z = 0.0;
  57189. this._cam_axisZ.x = 0.0;
  57190. this._cam_axisZ.y = 0.0;
  57191. this._cam_axisZ.z = 1.0;
  57192. // cases when the World Matrix is to be computed first
  57193. if (this.billboard || this._depthSort) {
  57194. this.mesh.computeWorldMatrix(true);
  57195. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  57196. }
  57197. // if the particles will always face the camera
  57198. if (this.billboard) {
  57199. // compute the camera position and un-rotate it by the current mesh rotation
  57200. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  57201. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57202. this._cam_axisZ.normalize();
  57203. // same for camera up vector extracted from the cam view matrix
  57204. var view = this._camera.getViewMatrix(true);
  57205. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  57206. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57207. this._cam_axisY.normalize();
  57208. this._cam_axisX.normalize();
  57209. }
  57210. // if depthSort, compute the camera global position in the mesh local system
  57211. if (this._depthSort) {
  57212. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  57213. }
  57214. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57215. var idx = 0; // current position index in the global array positions32
  57216. var index = 0; // position start index in the global array positions32 of the current particle
  57217. var colidx = 0; // current color index in the global array colors32
  57218. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  57219. var uvidx = 0; // current uv index in the global array uvs32
  57220. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  57221. var pt = 0; // current index in the particle model shape
  57222. if (this.mesh.isFacetDataEnabled) {
  57223. this._computeBoundingBox = true;
  57224. }
  57225. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  57226. if (this._computeBoundingBox) {
  57227. if (start == 0 && end == this.nbParticles - 1) {
  57228. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57229. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57230. }
  57231. else {
  57232. if (this.mesh._boundingInfo) {
  57233. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  57234. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  57235. }
  57236. }
  57237. }
  57238. // particle loop
  57239. index = this.particles[start]._pos;
  57240. var vpos = (index / 3) | 0;
  57241. colorIndex = vpos * 4;
  57242. uvIndex = vpos * 2;
  57243. for (var p = start; p <= end; p++) {
  57244. this._particle = this.particles[p];
  57245. this._shape = this._particle._model._shape;
  57246. this._shapeUV = this._particle._model._shapeUV;
  57247. // call to custom user function to update the particle properties
  57248. this.updateParticle(this._particle);
  57249. // camera-particle distance for depth sorting
  57250. if (this._depthSort && this._depthSortParticles) {
  57251. var dsp = this.depthSortedParticles[p];
  57252. dsp.ind = this._particle._ind;
  57253. dsp.indicesLength = this._particle._model._indicesLength;
  57254. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  57255. }
  57256. // skip the computations for inactive or already invisible particles
  57257. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  57258. // increment indexes for the next particle
  57259. pt = this._shape.length;
  57260. index += pt * 3;
  57261. colorIndex += pt * 4;
  57262. uvIndex += pt * 2;
  57263. continue;
  57264. }
  57265. if (this._particle.isVisible) {
  57266. this._particle._stillInvisible = false; // un-mark permanent invisibility
  57267. this._particleHasParent = (this._particle.parentId !== null);
  57268. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57269. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57270. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57271. // particle rotation matrix
  57272. if (this.billboard) {
  57273. this._particle.rotation.x = 0.0;
  57274. this._particle.rotation.y = 0.0;
  57275. }
  57276. if (this._computeParticleRotation || this.billboard) {
  57277. if (this._particle.rotationQuaternion) {
  57278. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57279. }
  57280. else {
  57281. this._yaw = this._particle.rotation.y;
  57282. this._pitch = this._particle.rotation.x;
  57283. this._roll = this._particle.rotation.z;
  57284. this._quaternionRotationYPR();
  57285. }
  57286. this._quaternionToRotationMatrix();
  57287. }
  57288. if (this._particleHasParent) {
  57289. this._parent = this.particles[this._particle.parentId];
  57290. 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];
  57291. 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];
  57292. 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];
  57293. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  57294. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  57295. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  57296. if (this._computeParticleRotation || this.billboard) {
  57297. 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];
  57298. 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];
  57299. 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];
  57300. 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];
  57301. 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];
  57302. 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];
  57303. 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];
  57304. 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];
  57305. 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];
  57306. }
  57307. }
  57308. else {
  57309. this._particle._globalPosition.x = this._particle.position.x;
  57310. this._particle._globalPosition.y = this._particle.position.y;
  57311. this._particle._globalPosition.z = this._particle.position.z;
  57312. if (this._computeParticleRotation || this.billboard) {
  57313. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  57314. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  57315. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  57316. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  57317. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  57318. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  57319. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  57320. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  57321. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  57322. }
  57323. }
  57324. if (this._particle.translateFromPivot) {
  57325. this._pivotBackTranslation.x = 0.0;
  57326. this._pivotBackTranslation.y = 0.0;
  57327. this._pivotBackTranslation.z = 0.0;
  57328. }
  57329. else {
  57330. this._pivotBackTranslation.x = this._scaledPivot.x;
  57331. this._pivotBackTranslation.y = this._scaledPivot.y;
  57332. this._pivotBackTranslation.z = this._scaledPivot.z;
  57333. }
  57334. // particle vertex loop
  57335. for (pt = 0; pt < this._shape.length; pt++) {
  57336. idx = index + pt * 3;
  57337. colidx = colorIndex + pt * 4;
  57338. uvidx = uvIndex + pt * 2;
  57339. this._vertex.x = this._shape[pt].x;
  57340. this._vertex.y = this._shape[pt].y;
  57341. this._vertex.z = this._shape[pt].z;
  57342. if (this._computeParticleVertex) {
  57343. this.updateParticleVertex(this._particle, this._vertex, pt);
  57344. }
  57345. // positions
  57346. this._vertex.x *= this._particle.scaling.x;
  57347. this._vertex.y *= this._particle.scaling.y;
  57348. this._vertex.z *= this._particle.scaling.z;
  57349. this._vertex.x -= this._scaledPivot.x;
  57350. this._vertex.y -= this._scaledPivot.y;
  57351. this._vertex.z -= this._scaledPivot.z;
  57352. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57353. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57354. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57355. this._rotated.x += this._pivotBackTranslation.x;
  57356. this._rotated.y += this._pivotBackTranslation.y;
  57357. this._rotated.z += this._pivotBackTranslation.z;
  57358. 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;
  57359. 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;
  57360. 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;
  57361. if (this._computeBoundingBox) {
  57362. if (this._positions32[idx] < this._minimum.x) {
  57363. this._minimum.x = this._positions32[idx];
  57364. }
  57365. if (this._positions32[idx] > this._maximum.x) {
  57366. this._maximum.x = this._positions32[idx];
  57367. }
  57368. if (this._positions32[idx + 1] < this._minimum.y) {
  57369. this._minimum.y = this._positions32[idx + 1];
  57370. }
  57371. if (this._positions32[idx + 1] > this._maximum.y) {
  57372. this._maximum.y = this._positions32[idx + 1];
  57373. }
  57374. if (this._positions32[idx + 2] < this._minimum.z) {
  57375. this._minimum.z = this._positions32[idx + 2];
  57376. }
  57377. if (this._positions32[idx + 2] > this._maximum.z) {
  57378. this._maximum.z = this._positions32[idx + 2];
  57379. }
  57380. }
  57381. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  57382. if (!this._computeParticleVertex) {
  57383. this._normal.x = this._fixedNormal32[idx];
  57384. this._normal.y = this._fixedNormal32[idx + 1];
  57385. this._normal.z = this._fixedNormal32[idx + 2];
  57386. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  57387. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  57388. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  57389. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57390. 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;
  57391. 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;
  57392. }
  57393. if (this._computeParticleColor && this._particle.color) {
  57394. this._colors32[colidx] = this._particle.color.r;
  57395. this._colors32[colidx + 1] = this._particle.color.g;
  57396. this._colors32[colidx + 2] = this._particle.color.b;
  57397. this._colors32[colidx + 3] = this._particle.color.a;
  57398. }
  57399. if (this._computeParticleTexture) {
  57400. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57401. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57402. }
  57403. }
  57404. }
  57405. else {
  57406. this._particle._stillInvisible = true; // mark the particle as invisible
  57407. for (pt = 0; pt < this._shape.length; pt++) {
  57408. idx = index + pt * 3;
  57409. colidx = colorIndex + pt * 4;
  57410. uvidx = uvIndex + pt * 2;
  57411. this._positions32[idx] = 0.0;
  57412. this._positions32[idx + 1] = 0.0;
  57413. this._positions32[idx + 2] = 0.0;
  57414. this._normals32[idx] = 0.0;
  57415. this._normals32[idx + 1] = 0.0;
  57416. this._normals32[idx + 2] = 0.0;
  57417. if (this._computeParticleColor && this._particle.color) {
  57418. this._colors32[colidx] = this._particle.color.r;
  57419. this._colors32[colidx + 1] = this._particle.color.g;
  57420. this._colors32[colidx + 2] = this._particle.color.b;
  57421. this._colors32[colidx + 3] = this._particle.color.a;
  57422. }
  57423. if (this._computeParticleTexture) {
  57424. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57425. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57426. }
  57427. }
  57428. }
  57429. // if the particle intersections must be computed : update the bbInfo
  57430. if (this._particlesIntersect) {
  57431. var bInfo = this._particle._boundingInfo;
  57432. var bBox = bInfo.boundingBox;
  57433. var bSphere = bInfo.boundingSphere;
  57434. if (!this._bSphereOnly) {
  57435. // place, scale and rotate the particle bbox within the SPS local system, then update it
  57436. for (var b = 0; b < bBox.vectors.length; b++) {
  57437. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  57438. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  57439. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  57440. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57441. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57442. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57443. 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;
  57444. 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;
  57445. 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;
  57446. }
  57447. bBox._update(this.mesh._worldMatrix);
  57448. }
  57449. // place and scale the particle bouding sphere in the SPS local system, then update it
  57450. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  57451. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  57452. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  57453. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  57454. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  57455. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  57456. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  57457. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  57458. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  57459. 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));
  57460. bSphere._update(this.mesh._worldMatrix);
  57461. }
  57462. // increment indexes for the next particle
  57463. index = idx + 3;
  57464. colorIndex = colidx + 4;
  57465. uvIndex = uvidx + 2;
  57466. }
  57467. // if the VBO must be updated
  57468. if (update) {
  57469. if (this._computeParticleColor) {
  57470. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57471. }
  57472. if (this._computeParticleTexture) {
  57473. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57474. }
  57475. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57476. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  57477. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  57478. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57479. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  57480. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  57481. for (var i = 0; i < this._normals32.length; i++) {
  57482. this._fixedNormal32[i] = this._normals32[i];
  57483. }
  57484. }
  57485. if (!this.mesh.areNormalsFrozen) {
  57486. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57487. }
  57488. }
  57489. if (this._depthSort && this._depthSortParticles) {
  57490. this.depthSortedParticles.sort(this._depthSortFunction);
  57491. var dspl = this.depthSortedParticles.length;
  57492. var sorted = 0;
  57493. var lind = 0;
  57494. var sind = 0;
  57495. var sid = 0;
  57496. for (sorted = 0; sorted < dspl; sorted++) {
  57497. lind = this.depthSortedParticles[sorted].indicesLength;
  57498. sind = this.depthSortedParticles[sorted].ind;
  57499. for (var i = 0; i < lind; i++) {
  57500. this._indices32[sid] = this._indices[sind + i];
  57501. sid++;
  57502. }
  57503. }
  57504. this.mesh.updateIndices(this._indices32);
  57505. }
  57506. }
  57507. if (this._computeBoundingBox) {
  57508. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57509. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57510. }
  57511. this.afterUpdateParticles(start, end, update);
  57512. return this;
  57513. };
  57514. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57515. this._halfroll = this._roll * 0.5;
  57516. this._halfpitch = this._pitch * 0.5;
  57517. this._halfyaw = this._yaw * 0.5;
  57518. this._sinRoll = Math.sin(this._halfroll);
  57519. this._cosRoll = Math.cos(this._halfroll);
  57520. this._sinPitch = Math.sin(this._halfpitch);
  57521. this._cosPitch = Math.cos(this._halfpitch);
  57522. this._sinYaw = Math.sin(this._halfyaw);
  57523. this._cosYaw = Math.cos(this._halfyaw);
  57524. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  57525. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  57526. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  57527. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  57528. };
  57529. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57530. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57531. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57532. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57533. this._rotMatrix.m[3] = 0;
  57534. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57535. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57536. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57537. this._rotMatrix.m[7] = 0;
  57538. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57539. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57540. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57541. this._rotMatrix.m[11] = 0;
  57542. this._rotMatrix.m[12] = 0;
  57543. this._rotMatrix.m[13] = 0;
  57544. this._rotMatrix.m[14] = 0;
  57545. this._rotMatrix.m[15] = 1.0;
  57546. };
  57547. /**
  57548. * Disposes the SPS.
  57549. */
  57550. SolidParticleSystem.prototype.dispose = function () {
  57551. this.mesh.dispose();
  57552. this.vars = null;
  57553. // drop references to internal big arrays for the GC
  57554. this._positions = null;
  57555. this._indices = null;
  57556. this._normals = null;
  57557. this._uvs = null;
  57558. this._colors = null;
  57559. this._indices32 = null;
  57560. this._positions32 = null;
  57561. this._normals32 = null;
  57562. this._fixedNormal32 = null;
  57563. this._uvs32 = null;
  57564. this._colors32 = null;
  57565. this.pickedParticles = null;
  57566. };
  57567. /**
  57568. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  57569. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57570. * @returns the SPS.
  57571. */
  57572. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  57573. if (!this._isVisibilityBoxLocked) {
  57574. this.mesh.refreshBoundingInfo();
  57575. }
  57576. return this;
  57577. };
  57578. /**
  57579. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  57580. * @param size the size (float) of the visibility box
  57581. * note : this doesn't lock the SPS mesh bounding box.
  57582. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57583. */
  57584. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  57585. var vis = size / 2;
  57586. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  57587. };
  57588. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  57589. /**
  57590. * Gets whether the SPS as always visible or not
  57591. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57592. */
  57593. get: function () {
  57594. return this._alwaysVisible;
  57595. },
  57596. /**
  57597. * Sets the SPS as always visible or not
  57598. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57599. */
  57600. set: function (val) {
  57601. this._alwaysVisible = val;
  57602. this.mesh.alwaysSelectAsActiveMesh = val;
  57603. },
  57604. enumerable: true,
  57605. configurable: true
  57606. });
  57607. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  57608. /**
  57609. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57610. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57611. */
  57612. get: function () {
  57613. return this._isVisibilityBoxLocked;
  57614. },
  57615. /**
  57616. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57617. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57618. */
  57619. set: function (val) {
  57620. this._isVisibilityBoxLocked = val;
  57621. var boundingInfo = this.mesh.getBoundingInfo();
  57622. boundingInfo.isLocked = val;
  57623. },
  57624. enumerable: true,
  57625. configurable: true
  57626. });
  57627. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  57628. /**
  57629. * Gets if `setParticles()` computes the particle rotations or not.
  57630. * Default value : true. The SPS is faster when it's set to false.
  57631. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57632. */
  57633. get: function () {
  57634. return this._computeParticleRotation;
  57635. },
  57636. /**
  57637. * Tells to `setParticles()` to compute the particle rotations or not.
  57638. * Default value : true. The SPS is faster when it's set to false.
  57639. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57640. */
  57641. set: function (val) {
  57642. this._computeParticleRotation = val;
  57643. },
  57644. enumerable: true,
  57645. configurable: true
  57646. });
  57647. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  57648. /**
  57649. * Gets if `setParticles()` computes the particle colors or not.
  57650. * Default value : true. The SPS is faster when it's set to false.
  57651. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57652. */
  57653. get: function () {
  57654. return this._computeParticleColor;
  57655. },
  57656. /**
  57657. * Tells to `setParticles()` to compute the particle colors or not.
  57658. * Default value : true. The SPS is faster when it's set to false.
  57659. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57660. */
  57661. set: function (val) {
  57662. this._computeParticleColor = val;
  57663. },
  57664. enumerable: true,
  57665. configurable: true
  57666. });
  57667. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  57668. /**
  57669. * Gets if `setParticles()` computes the particle textures or not.
  57670. * Default value : true. The SPS is faster when it's set to false.
  57671. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  57672. */
  57673. get: function () {
  57674. return this._computeParticleTexture;
  57675. },
  57676. set: function (val) {
  57677. this._computeParticleTexture = val;
  57678. },
  57679. enumerable: true,
  57680. configurable: true
  57681. });
  57682. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  57683. /**
  57684. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  57685. * Default value : false. The SPS is faster when it's set to false.
  57686. * Note : the particle custom vertex positions aren't stored values.
  57687. */
  57688. get: function () {
  57689. return this._computeParticleVertex;
  57690. },
  57691. /**
  57692. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  57693. * Default value : false. The SPS is faster when it's set to false.
  57694. * Note : the particle custom vertex positions aren't stored values.
  57695. */
  57696. set: function (val) {
  57697. this._computeParticleVertex = val;
  57698. },
  57699. enumerable: true,
  57700. configurable: true
  57701. });
  57702. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  57703. /**
  57704. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  57705. */
  57706. get: function () {
  57707. return this._computeBoundingBox;
  57708. },
  57709. /**
  57710. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  57711. */
  57712. set: function (val) {
  57713. this._computeBoundingBox = val;
  57714. },
  57715. enumerable: true,
  57716. configurable: true
  57717. });
  57718. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  57719. /**
  57720. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  57721. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  57722. * Default : `true`
  57723. */
  57724. get: function () {
  57725. return this._depthSortParticles;
  57726. },
  57727. /**
  57728. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  57729. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  57730. * Default : `true`
  57731. */
  57732. set: function (val) {
  57733. this._depthSortParticles = val;
  57734. },
  57735. enumerable: true,
  57736. configurable: true
  57737. });
  57738. // =======================================================================
  57739. // Particle behavior logic
  57740. // these following methods may be overwritten by the user to fit his needs
  57741. /**
  57742. * This function does nothing. It may be overwritten to set all the particle first values.
  57743. * The SPS doesn't call this function, you may have to call it by your own.
  57744. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57745. */
  57746. SolidParticleSystem.prototype.initParticles = function () {
  57747. };
  57748. /**
  57749. * This function does nothing. It may be overwritten to recycle a particle.
  57750. * The SPS doesn't call this function, you may have to call it by your own.
  57751. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57752. * @param particle The particle to recycle
  57753. * @returns the recycled particle
  57754. */
  57755. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  57756. return particle;
  57757. };
  57758. /**
  57759. * Updates a particle : this function should be overwritten by the user.
  57760. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  57761. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57762. * @example : just set a particle position or velocity and recycle conditions
  57763. * @param particle The particle to update
  57764. * @returns the updated particle
  57765. */
  57766. SolidParticleSystem.prototype.updateParticle = function (particle) {
  57767. return particle;
  57768. };
  57769. /**
  57770. * Updates a vertex of a particle : it can be overwritten by the user.
  57771. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  57772. * @param particle the current particle
  57773. * @param vertex the current index of the current particle
  57774. * @param pt the index of the current vertex in the particle shape
  57775. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  57776. * @example : just set a vertex particle position
  57777. * @returns the updated vertex
  57778. */
  57779. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  57780. return vertex;
  57781. };
  57782. /**
  57783. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  57784. * This does nothing and may be overwritten by the user.
  57785. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57786. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57787. * @param update the boolean update value actually passed to setParticles()
  57788. */
  57789. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  57790. };
  57791. /**
  57792. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  57793. * This will be passed three parameters.
  57794. * This does nothing and may be overwritten by the user.
  57795. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57796. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57797. * @param update the boolean update value actually passed to setParticles()
  57798. */
  57799. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  57800. };
  57801. return SolidParticleSystem;
  57802. }());
  57803. BABYLON.SolidParticleSystem = SolidParticleSystem;
  57804. })(BABYLON || (BABYLON = {}));
  57805. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  57806. "use strict";
  57807. var BABYLON;
  57808. (function (BABYLON) {
  57809. var ShaderMaterial = /** @class */ (function (_super) {
  57810. __extends(ShaderMaterial, _super);
  57811. function ShaderMaterial(name, scene, shaderPath, options) {
  57812. var _this = _super.call(this, name, scene) || this;
  57813. _this._textures = {};
  57814. _this._textureArrays = {};
  57815. _this._floats = {};
  57816. _this._ints = {};
  57817. _this._floatsArrays = {};
  57818. _this._colors3 = {};
  57819. _this._colors3Arrays = {};
  57820. _this._colors4 = {};
  57821. _this._vectors2 = {};
  57822. _this._vectors3 = {};
  57823. _this._vectors4 = {};
  57824. _this._matrices = {};
  57825. _this._matrices3x3 = {};
  57826. _this._matrices2x2 = {};
  57827. _this._vectors2Arrays = {};
  57828. _this._vectors3Arrays = {};
  57829. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57830. _this._shaderPath = shaderPath;
  57831. options.needAlphaBlending = options.needAlphaBlending || false;
  57832. options.needAlphaTesting = options.needAlphaTesting || false;
  57833. options.attributes = options.attributes || ["position", "normal", "uv"];
  57834. options.uniforms = options.uniforms || ["worldViewProjection"];
  57835. options.uniformBuffers = options.uniformBuffers || [];
  57836. options.samplers = options.samplers || [];
  57837. options.defines = options.defines || [];
  57838. _this._options = options;
  57839. return _this;
  57840. }
  57841. ShaderMaterial.prototype.getClassName = function () {
  57842. return "ShaderMaterial";
  57843. };
  57844. ShaderMaterial.prototype.needAlphaBlending = function () {
  57845. return this._options.needAlphaBlending;
  57846. };
  57847. ShaderMaterial.prototype.needAlphaTesting = function () {
  57848. return this._options.needAlphaTesting;
  57849. };
  57850. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57851. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57852. this._options.uniforms.push(uniformName);
  57853. }
  57854. };
  57855. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57856. if (this._options.samplers.indexOf(name) === -1) {
  57857. this._options.samplers.push(name);
  57858. }
  57859. this._textures[name] = texture;
  57860. return this;
  57861. };
  57862. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57863. if (this._options.samplers.indexOf(name) === -1) {
  57864. this._options.samplers.push(name);
  57865. }
  57866. this._checkUniform(name);
  57867. this._textureArrays[name] = textures;
  57868. return this;
  57869. };
  57870. ShaderMaterial.prototype.setFloat = function (name, value) {
  57871. this._checkUniform(name);
  57872. this._floats[name] = value;
  57873. return this;
  57874. };
  57875. ShaderMaterial.prototype.setInt = function (name, value) {
  57876. this._checkUniform(name);
  57877. this._ints[name] = value;
  57878. return this;
  57879. };
  57880. ShaderMaterial.prototype.setFloats = function (name, value) {
  57881. this._checkUniform(name);
  57882. this._floatsArrays[name] = value;
  57883. return this;
  57884. };
  57885. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57886. this._checkUniform(name);
  57887. this._colors3[name] = value;
  57888. return this;
  57889. };
  57890. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57891. this._checkUniform(name);
  57892. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57893. color.toArray(arr, arr.length);
  57894. return arr;
  57895. }, []);
  57896. return this;
  57897. };
  57898. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57899. this._checkUniform(name);
  57900. this._colors4[name] = value;
  57901. return this;
  57902. };
  57903. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57904. this._checkUniform(name);
  57905. this._vectors2[name] = value;
  57906. return this;
  57907. };
  57908. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57909. this._checkUniform(name);
  57910. this._vectors3[name] = value;
  57911. return this;
  57912. };
  57913. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57914. this._checkUniform(name);
  57915. this._vectors4[name] = value;
  57916. return this;
  57917. };
  57918. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57919. this._checkUniform(name);
  57920. this._matrices[name] = value;
  57921. return this;
  57922. };
  57923. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57924. this._checkUniform(name);
  57925. this._matrices3x3[name] = value;
  57926. return this;
  57927. };
  57928. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57929. this._checkUniform(name);
  57930. this._matrices2x2[name] = value;
  57931. return this;
  57932. };
  57933. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57934. this._checkUniform(name);
  57935. this._vectors2Arrays[name] = value;
  57936. return this;
  57937. };
  57938. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57939. this._checkUniform(name);
  57940. this._vectors3Arrays[name] = value;
  57941. return this;
  57942. };
  57943. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57944. if (!mesh) {
  57945. return true;
  57946. }
  57947. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57948. return false;
  57949. }
  57950. return false;
  57951. };
  57952. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57953. var scene = this.getScene();
  57954. var engine = scene.getEngine();
  57955. if (!this.checkReadyOnEveryCall) {
  57956. if (this._renderId === scene.getRenderId()) {
  57957. if (this._checkCache(scene, mesh, useInstances)) {
  57958. return true;
  57959. }
  57960. }
  57961. }
  57962. // Instances
  57963. var defines = [];
  57964. var attribs = [];
  57965. var fallbacks = new BABYLON.EffectFallbacks();
  57966. if (useInstances) {
  57967. defines.push("#define INSTANCES");
  57968. }
  57969. for (var index = 0; index < this._options.defines.length; index++) {
  57970. defines.push(this._options.defines[index]);
  57971. }
  57972. for (var index = 0; index < this._options.attributes.length; index++) {
  57973. attribs.push(this._options.attributes[index]);
  57974. }
  57975. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57976. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57977. defines.push("#define VERTEXCOLOR");
  57978. }
  57979. // Bones
  57980. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57981. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57982. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57983. if (mesh.numBoneInfluencers > 4) {
  57984. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57985. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57986. }
  57987. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57988. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57989. fallbacks.addCPUSkinningFallback(0, mesh);
  57990. if (this._options.uniforms.indexOf("mBones") === -1) {
  57991. this._options.uniforms.push("mBones");
  57992. }
  57993. }
  57994. else {
  57995. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57996. }
  57997. // Textures
  57998. for (var name in this._textures) {
  57999. if (!this._textures[name].isReady()) {
  58000. return false;
  58001. }
  58002. }
  58003. // Alpha test
  58004. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58005. defines.push("#define ALPHATEST");
  58006. }
  58007. var previousEffect = this._effect;
  58008. var join = defines.join("\n");
  58009. this._effect = engine.createEffect(this._shaderPath, {
  58010. attributes: attribs,
  58011. uniformsNames: this._options.uniforms,
  58012. uniformBuffersNames: this._options.uniformBuffers,
  58013. samplers: this._options.samplers,
  58014. defines: join,
  58015. fallbacks: fallbacks,
  58016. onCompiled: this.onCompiled,
  58017. onError: this.onError
  58018. }, engine);
  58019. if (!this._effect.isReady()) {
  58020. return false;
  58021. }
  58022. if (previousEffect !== this._effect) {
  58023. scene.resetCachedMaterial();
  58024. }
  58025. this._renderId = scene.getRenderId();
  58026. return true;
  58027. };
  58028. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58029. var scene = this.getScene();
  58030. if (!this._effect) {
  58031. return;
  58032. }
  58033. if (this._options.uniforms.indexOf("world") !== -1) {
  58034. this._effect.setMatrix("world", world);
  58035. }
  58036. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58037. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58038. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58039. }
  58040. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58041. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58042. }
  58043. };
  58044. ShaderMaterial.prototype.bind = function (world, mesh) {
  58045. // Std values
  58046. this.bindOnlyWorldMatrix(world);
  58047. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58048. if (this._options.uniforms.indexOf("view") !== -1) {
  58049. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58050. }
  58051. if (this._options.uniforms.indexOf("projection") !== -1) {
  58052. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58053. }
  58054. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58055. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58056. }
  58057. // Bones
  58058. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58059. var name;
  58060. // Texture
  58061. for (name in this._textures) {
  58062. this._effect.setTexture(name, this._textures[name]);
  58063. }
  58064. // Texture arrays
  58065. for (name in this._textureArrays) {
  58066. this._effect.setTextureArray(name, this._textureArrays[name]);
  58067. }
  58068. // Int
  58069. for (name in this._ints) {
  58070. this._effect.setInt(name, this._ints[name]);
  58071. }
  58072. // Float
  58073. for (name in this._floats) {
  58074. this._effect.setFloat(name, this._floats[name]);
  58075. }
  58076. // Floats
  58077. for (name in this._floatsArrays) {
  58078. this._effect.setArray(name, this._floatsArrays[name]);
  58079. }
  58080. // Color3
  58081. for (name in this._colors3) {
  58082. this._effect.setColor3(name, this._colors3[name]);
  58083. }
  58084. for (name in this._colors3Arrays) {
  58085. this._effect.setArray3(name, this._colors3Arrays[name]);
  58086. }
  58087. // Color4
  58088. for (name in this._colors4) {
  58089. var color = this._colors4[name];
  58090. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58091. }
  58092. // Vector2
  58093. for (name in this._vectors2) {
  58094. this._effect.setVector2(name, this._vectors2[name]);
  58095. }
  58096. // Vector3
  58097. for (name in this._vectors3) {
  58098. this._effect.setVector3(name, this._vectors3[name]);
  58099. }
  58100. // Vector4
  58101. for (name in this._vectors4) {
  58102. this._effect.setVector4(name, this._vectors4[name]);
  58103. }
  58104. // Matrix
  58105. for (name in this._matrices) {
  58106. this._effect.setMatrix(name, this._matrices[name]);
  58107. }
  58108. // Matrix 3x3
  58109. for (name in this._matrices3x3) {
  58110. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58111. }
  58112. // Matrix 2x2
  58113. for (name in this._matrices2x2) {
  58114. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58115. }
  58116. // Vector2Array
  58117. for (name in this._vectors2Arrays) {
  58118. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58119. }
  58120. // Vector3Array
  58121. for (name in this._vectors3Arrays) {
  58122. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58123. }
  58124. }
  58125. this._afterBind(mesh);
  58126. };
  58127. ShaderMaterial.prototype.getActiveTextures = function () {
  58128. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58129. for (var name in this._textures) {
  58130. activeTextures.push(this._textures[name]);
  58131. }
  58132. for (var name in this._textureArrays) {
  58133. var array = this._textureArrays[name];
  58134. for (var index = 0; index < array.length; index++) {
  58135. activeTextures.push(array[index]);
  58136. }
  58137. }
  58138. return activeTextures;
  58139. };
  58140. ShaderMaterial.prototype.hasTexture = function (texture) {
  58141. if (_super.prototype.hasTexture.call(this, texture)) {
  58142. return true;
  58143. }
  58144. for (var name in this._textures) {
  58145. if (this._textures[name] === texture) {
  58146. return true;
  58147. }
  58148. }
  58149. for (var name in this._textureArrays) {
  58150. var array = this._textureArrays[name];
  58151. for (var index = 0; index < array.length; index++) {
  58152. if (array[index] === texture) {
  58153. return true;
  58154. }
  58155. }
  58156. }
  58157. return false;
  58158. };
  58159. ShaderMaterial.prototype.clone = function (name) {
  58160. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58161. return newShaderMaterial;
  58162. };
  58163. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58164. if (forceDisposeTextures) {
  58165. var name;
  58166. for (name in this._textures) {
  58167. this._textures[name].dispose();
  58168. }
  58169. for (name in this._textureArrays) {
  58170. var array = this._textureArrays[name];
  58171. for (var index = 0; index < array.length; index++) {
  58172. array[index].dispose();
  58173. }
  58174. }
  58175. }
  58176. this._textures = {};
  58177. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58178. };
  58179. ShaderMaterial.prototype.serialize = function () {
  58180. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58181. serializationObject.customType = "BABYLON.ShaderMaterial";
  58182. serializationObject.options = this._options;
  58183. serializationObject.shaderPath = this._shaderPath;
  58184. var name;
  58185. // Texture
  58186. serializationObject.textures = {};
  58187. for (name in this._textures) {
  58188. serializationObject.textures[name] = this._textures[name].serialize();
  58189. }
  58190. // Texture arrays
  58191. serializationObject.textureArrays = {};
  58192. for (name in this._textureArrays) {
  58193. serializationObject.textureArrays[name] = [];
  58194. var array = this._textureArrays[name];
  58195. for (var index = 0; index < array.length; index++) {
  58196. serializationObject.textureArrays[name].push(array[index].serialize());
  58197. }
  58198. }
  58199. // Float
  58200. serializationObject.floats = {};
  58201. for (name in this._floats) {
  58202. serializationObject.floats[name] = this._floats[name];
  58203. }
  58204. // Float s
  58205. serializationObject.FloatArrays = {};
  58206. for (name in this._floatsArrays) {
  58207. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58208. }
  58209. // Color3
  58210. serializationObject.colors3 = {};
  58211. for (name in this._colors3) {
  58212. serializationObject.colors3[name] = this._colors3[name].asArray();
  58213. }
  58214. // Color3 array
  58215. serializationObject.colors3Arrays = {};
  58216. for (name in this._colors3Arrays) {
  58217. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58218. }
  58219. // Color4
  58220. serializationObject.colors4 = {};
  58221. for (name in this._colors4) {
  58222. serializationObject.colors4[name] = this._colors4[name].asArray();
  58223. }
  58224. // Vector2
  58225. serializationObject.vectors2 = {};
  58226. for (name in this._vectors2) {
  58227. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58228. }
  58229. // Vector3
  58230. serializationObject.vectors3 = {};
  58231. for (name in this._vectors3) {
  58232. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58233. }
  58234. // Vector4
  58235. serializationObject.vectors4 = {};
  58236. for (name in this._vectors4) {
  58237. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58238. }
  58239. // Matrix
  58240. serializationObject.matrices = {};
  58241. for (name in this._matrices) {
  58242. serializationObject.matrices[name] = this._matrices[name].asArray();
  58243. }
  58244. // Matrix 3x3
  58245. serializationObject.matrices3x3 = {};
  58246. for (name in this._matrices3x3) {
  58247. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58248. }
  58249. // Matrix 2x2
  58250. serializationObject.matrices2x2 = {};
  58251. for (name in this._matrices2x2) {
  58252. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58253. }
  58254. // Vector2Array
  58255. serializationObject.vectors2Arrays = {};
  58256. for (name in this._vectors2Arrays) {
  58257. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58258. }
  58259. // Vector3Array
  58260. serializationObject.vectors3Arrays = {};
  58261. for (name in this._vectors3Arrays) {
  58262. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58263. }
  58264. return serializationObject;
  58265. };
  58266. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58267. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58268. var name;
  58269. // Texture
  58270. for (name in source.textures) {
  58271. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58272. }
  58273. // Texture arrays
  58274. for (name in source.textureArrays) {
  58275. var array = source.textureArrays[name];
  58276. var textureArray = new Array();
  58277. for (var index = 0; index < array.length; index++) {
  58278. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58279. }
  58280. material.setTextureArray(name, textureArray);
  58281. }
  58282. // Float
  58283. for (name in source.floats) {
  58284. material.setFloat(name, source.floats[name]);
  58285. }
  58286. // Float s
  58287. for (name in source.floatsArrays) {
  58288. material.setFloats(name, source.floatsArrays[name]);
  58289. }
  58290. // Color3
  58291. for (name in source.colors3) {
  58292. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58293. }
  58294. // Color3 arrays
  58295. for (name in source.colors3Arrays) {
  58296. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58297. if (i % 3 === 0) {
  58298. arr.push([num]);
  58299. }
  58300. else {
  58301. arr[arr.length - 1].push(num);
  58302. }
  58303. return arr;
  58304. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58305. material.setColor3Array(name, colors);
  58306. }
  58307. // Color4
  58308. for (name in source.colors4) {
  58309. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58310. }
  58311. // Vector2
  58312. for (name in source.vectors2) {
  58313. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58314. }
  58315. // Vector3
  58316. for (name in source.vectors3) {
  58317. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58318. }
  58319. // Vector4
  58320. for (name in source.vectors4) {
  58321. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58322. }
  58323. // Matrix
  58324. for (name in source.matrices) {
  58325. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58326. }
  58327. // Matrix 3x3
  58328. for (name in source.matrices3x3) {
  58329. material.setMatrix3x3(name, source.matrices3x3[name]);
  58330. }
  58331. // Matrix 2x2
  58332. for (name in source.matrices2x2) {
  58333. material.setMatrix2x2(name, source.matrices2x2[name]);
  58334. }
  58335. // Vector2Array
  58336. for (name in source.vectors2Arrays) {
  58337. material.setArray2(name, source.vectors2Arrays[name]);
  58338. }
  58339. // Vector3Array
  58340. for (name in source.vectors3Arrays) {
  58341. material.setArray3(name, source.vectors3Arrays[name]);
  58342. }
  58343. return material;
  58344. };
  58345. return ShaderMaterial;
  58346. }(BABYLON.Material));
  58347. BABYLON.ShaderMaterial = ShaderMaterial;
  58348. })(BABYLON || (BABYLON = {}));
  58349. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58350. "use strict";
  58351. var BABYLON;
  58352. (function (BABYLON) {
  58353. var GroundMesh = /** @class */ (function (_super) {
  58354. __extends(GroundMesh, _super);
  58355. function GroundMesh(name, scene) {
  58356. var _this = _super.call(this, name, scene) || this;
  58357. _this.generateOctree = false;
  58358. return _this;
  58359. }
  58360. GroundMesh.prototype.getClassName = function () {
  58361. return "GroundMesh";
  58362. };
  58363. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58364. get: function () {
  58365. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58366. },
  58367. enumerable: true,
  58368. configurable: true
  58369. });
  58370. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58371. get: function () {
  58372. return this._subdivisionsX;
  58373. },
  58374. enumerable: true,
  58375. configurable: true
  58376. });
  58377. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58378. get: function () {
  58379. return this._subdivisionsY;
  58380. },
  58381. enumerable: true,
  58382. configurable: true
  58383. });
  58384. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58385. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58386. this._subdivisionsX = chunksCount;
  58387. this._subdivisionsY = chunksCount;
  58388. this.subdivide(chunksCount);
  58389. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58390. };
  58391. /**
  58392. * Returns a height (y) value in the Worl system :
  58393. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58394. * Returns the ground y position if (x, z) are outside the ground surface.
  58395. */
  58396. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58397. var world = this.getWorldMatrix();
  58398. var invMat = BABYLON.Tmp.Matrix[5];
  58399. world.invertToRef(invMat);
  58400. var tmpVect = BABYLON.Tmp.Vector3[8];
  58401. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58402. x = tmpVect.x;
  58403. z = tmpVect.z;
  58404. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58405. return this.position.y;
  58406. }
  58407. if (!this._heightQuads || this._heightQuads.length == 0) {
  58408. this._initHeightQuads();
  58409. this._computeHeightQuads();
  58410. }
  58411. var facet = this._getFacetAt(x, z);
  58412. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58413. // return y in the World system
  58414. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58415. return tmpVect.y;
  58416. };
  58417. /**
  58418. * Returns a normalized vector (Vector3) orthogonal to the ground
  58419. * at the ground coordinates (x, z) expressed in the World system.
  58420. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58421. */
  58422. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58423. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58424. this.getNormalAtCoordinatesToRef(x, z, normal);
  58425. return normal;
  58426. };
  58427. /**
  58428. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58429. * at the ground coordinates (x, z) expressed in the World system.
  58430. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58431. * Returns the GroundMesh.
  58432. */
  58433. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58434. var world = this.getWorldMatrix();
  58435. var tmpMat = BABYLON.Tmp.Matrix[5];
  58436. world.invertToRef(tmpMat);
  58437. var tmpVect = BABYLON.Tmp.Vector3[8];
  58438. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58439. x = tmpVect.x;
  58440. z = tmpVect.z;
  58441. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58442. return this;
  58443. }
  58444. if (!this._heightQuads || this._heightQuads.length == 0) {
  58445. this._initHeightQuads();
  58446. this._computeHeightQuads();
  58447. }
  58448. var facet = this._getFacetAt(x, z);
  58449. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58450. return this;
  58451. };
  58452. /**
  58453. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58454. * if the ground has been updated.
  58455. * This can be used in the render loop.
  58456. * Returns the GroundMesh.
  58457. */
  58458. GroundMesh.prototype.updateCoordinateHeights = function () {
  58459. if (!this._heightQuads || this._heightQuads.length == 0) {
  58460. this._initHeightQuads();
  58461. }
  58462. this._computeHeightQuads();
  58463. return this;
  58464. };
  58465. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58466. GroundMesh.prototype._getFacetAt = function (x, z) {
  58467. // retrieve col and row from x, z coordinates in the ground local system
  58468. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58469. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58470. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58471. var facet;
  58472. if (z < quad.slope.x * x + quad.slope.y) {
  58473. facet = quad.facet1;
  58474. }
  58475. else {
  58476. facet = quad.facet2;
  58477. }
  58478. return facet;
  58479. };
  58480. // Creates and populates the heightMap array with "facet" elements :
  58481. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58482. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58483. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58484. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58485. // Returns the GroundMesh.
  58486. GroundMesh.prototype._initHeightQuads = function () {
  58487. var subdivisionsX = this._subdivisionsX;
  58488. var subdivisionsY = this._subdivisionsY;
  58489. this._heightQuads = new Array();
  58490. for (var row = 0; row < subdivisionsY; row++) {
  58491. for (var col = 0; col < subdivisionsX; col++) {
  58492. 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) };
  58493. this._heightQuads[row * subdivisionsX + col] = quad;
  58494. }
  58495. }
  58496. return this;
  58497. };
  58498. // Compute each quad element values and update the the heightMap array :
  58499. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58500. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58501. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58502. // Returns the GroundMesh.
  58503. GroundMesh.prototype._computeHeightQuads = function () {
  58504. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58505. if (!positions) {
  58506. return this;
  58507. }
  58508. var v1 = BABYLON.Tmp.Vector3[3];
  58509. var v2 = BABYLON.Tmp.Vector3[2];
  58510. var v3 = BABYLON.Tmp.Vector3[1];
  58511. var v4 = BABYLON.Tmp.Vector3[0];
  58512. var v1v2 = BABYLON.Tmp.Vector3[4];
  58513. var v1v3 = BABYLON.Tmp.Vector3[5];
  58514. var v1v4 = BABYLON.Tmp.Vector3[6];
  58515. var norm1 = BABYLON.Tmp.Vector3[7];
  58516. var norm2 = BABYLON.Tmp.Vector3[8];
  58517. var i = 0;
  58518. var j = 0;
  58519. var k = 0;
  58520. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58521. var h = 0;
  58522. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58523. var d2 = 0;
  58524. var subdivisionsX = this._subdivisionsX;
  58525. var subdivisionsY = this._subdivisionsY;
  58526. for (var row = 0; row < subdivisionsY; row++) {
  58527. for (var col = 0; col < subdivisionsX; col++) {
  58528. i = col * 3;
  58529. j = row * (subdivisionsX + 1) * 3;
  58530. k = (row + 1) * (subdivisionsX + 1) * 3;
  58531. v1.x = positions[j + i];
  58532. v1.y = positions[j + i + 1];
  58533. v1.z = positions[j + i + 2];
  58534. v2.x = positions[j + i + 3];
  58535. v2.y = positions[j + i + 4];
  58536. v2.z = positions[j + i + 5];
  58537. v3.x = positions[k + i];
  58538. v3.y = positions[k + i + 1];
  58539. v3.z = positions[k + i + 2];
  58540. v4.x = positions[k + i + 3];
  58541. v4.y = positions[k + i + 4];
  58542. v4.z = positions[k + i + 5];
  58543. // 2D slope V1V4
  58544. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58545. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58546. // facet equations :
  58547. // we compute each facet normal vector
  58548. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58549. // we compute the value d by applying the equation to v1 which belongs to the plane
  58550. // then we store the facet equation in a Vector4
  58551. v2.subtractToRef(v1, v1v2);
  58552. v3.subtractToRef(v1, v1v3);
  58553. v4.subtractToRef(v1, v1v4);
  58554. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  58555. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  58556. norm1.normalize();
  58557. norm2.normalize();
  58558. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  58559. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  58560. var quad = this._heightQuads[row * subdivisionsX + col];
  58561. quad.slope.copyFromFloats(cd, h);
  58562. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  58563. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  58564. }
  58565. }
  58566. return this;
  58567. };
  58568. GroundMesh.prototype.serialize = function (serializationObject) {
  58569. _super.prototype.serialize.call(this, serializationObject);
  58570. serializationObject.subdivisionsX = this._subdivisionsX;
  58571. serializationObject.subdivisionsY = this._subdivisionsY;
  58572. serializationObject.minX = this._minX;
  58573. serializationObject.maxX = this._maxX;
  58574. serializationObject.minZ = this._minZ;
  58575. serializationObject.maxZ = this._maxZ;
  58576. serializationObject.width = this._width;
  58577. serializationObject.height = this._height;
  58578. };
  58579. GroundMesh.Parse = function (parsedMesh, scene) {
  58580. var result = new GroundMesh(parsedMesh.name, scene);
  58581. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  58582. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  58583. result._minX = parsedMesh.minX;
  58584. result._maxX = parsedMesh.maxX;
  58585. result._minZ = parsedMesh.minZ;
  58586. result._maxZ = parsedMesh.maxZ;
  58587. result._width = parsedMesh.width;
  58588. result._height = parsedMesh.height;
  58589. return result;
  58590. };
  58591. return GroundMesh;
  58592. }(BABYLON.Mesh));
  58593. BABYLON.GroundMesh = GroundMesh;
  58594. })(BABYLON || (BABYLON = {}));
  58595. //# sourceMappingURL=babylon.groundMesh.js.map
  58596. "use strict";
  58597. var BABYLON;
  58598. (function (BABYLON) {
  58599. /**
  58600. * Creates an instance based on a source mesh.
  58601. */
  58602. var InstancedMesh = /** @class */ (function (_super) {
  58603. __extends(InstancedMesh, _super);
  58604. function InstancedMesh(name, source) {
  58605. var _this = _super.call(this, name, source.getScene()) || this;
  58606. source.instances.push(_this);
  58607. _this._sourceMesh = source;
  58608. _this.position.copyFrom(source.position);
  58609. _this.rotation.copyFrom(source.rotation);
  58610. _this.scaling.copyFrom(source.scaling);
  58611. if (source.rotationQuaternion) {
  58612. _this.rotationQuaternion = source.rotationQuaternion.clone();
  58613. }
  58614. _this.infiniteDistance = source.infiniteDistance;
  58615. _this.setPivotMatrix(source.getPivotMatrix());
  58616. _this.refreshBoundingInfo();
  58617. _this._syncSubMeshes();
  58618. return _this;
  58619. }
  58620. /**
  58621. * Returns the string "InstancedMesh".
  58622. */
  58623. InstancedMesh.prototype.getClassName = function () {
  58624. return "InstancedMesh";
  58625. };
  58626. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  58627. // Methods
  58628. get: function () {
  58629. return this._sourceMesh.receiveShadows;
  58630. },
  58631. enumerable: true,
  58632. configurable: true
  58633. });
  58634. Object.defineProperty(InstancedMesh.prototype, "material", {
  58635. get: function () {
  58636. return this._sourceMesh.material;
  58637. },
  58638. enumerable: true,
  58639. configurable: true
  58640. });
  58641. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  58642. get: function () {
  58643. return this._sourceMesh.visibility;
  58644. },
  58645. enumerable: true,
  58646. configurable: true
  58647. });
  58648. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  58649. get: function () {
  58650. return this._sourceMesh.skeleton;
  58651. },
  58652. enumerable: true,
  58653. configurable: true
  58654. });
  58655. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  58656. get: function () {
  58657. return this._sourceMesh.renderingGroupId;
  58658. },
  58659. set: function (value) {
  58660. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  58661. return;
  58662. }
  58663. //no-op with warning
  58664. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  58665. },
  58666. enumerable: true,
  58667. configurable: true
  58668. });
  58669. /**
  58670. * Returns the total number of vertices (integer).
  58671. */
  58672. InstancedMesh.prototype.getTotalVertices = function () {
  58673. return this._sourceMesh.getTotalVertices();
  58674. };
  58675. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  58676. get: function () {
  58677. return this._sourceMesh;
  58678. },
  58679. enumerable: true,
  58680. configurable: true
  58681. });
  58682. /**
  58683. * Is this node ready to be used/rendered
  58684. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  58685. * @return {boolean} is it ready
  58686. */
  58687. InstancedMesh.prototype.isReady = function (completeCheck) {
  58688. if (completeCheck === void 0) { completeCheck = false; }
  58689. return this._sourceMesh.isReady(completeCheck, true);
  58690. };
  58691. /**
  58692. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58693. */
  58694. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58695. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  58696. };
  58697. /**
  58698. * Sets the vertex data of the mesh geometry for the requested `kind`.
  58699. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  58700. * The `data` are either a numeric array either a Float32Array.
  58701. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  58702. * 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).
  58703. * Note that a new underlying VertexBuffer object is created each call.
  58704. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58705. *
  58706. * Possible `kind` values :
  58707. * - BABYLON.VertexBuffer.PositionKind
  58708. * - BABYLON.VertexBuffer.UVKind
  58709. * - BABYLON.VertexBuffer.UV2Kind
  58710. * - BABYLON.VertexBuffer.UV3Kind
  58711. * - BABYLON.VertexBuffer.UV4Kind
  58712. * - BABYLON.VertexBuffer.UV5Kind
  58713. * - BABYLON.VertexBuffer.UV6Kind
  58714. * - BABYLON.VertexBuffer.ColorKind
  58715. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58716. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58717. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58718. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58719. *
  58720. * Returns the Mesh.
  58721. */
  58722. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58723. if (this.sourceMesh) {
  58724. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58725. }
  58726. return this.sourceMesh;
  58727. };
  58728. /**
  58729. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58730. * If the mesh has no geometry, it is simply returned as it is.
  58731. * The `data` are either a numeric array either a Float32Array.
  58732. * No new underlying VertexBuffer object is created.
  58733. * 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.
  58734. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58735. *
  58736. * Possible `kind` values :
  58737. * - BABYLON.VertexBuffer.PositionKind
  58738. * - BABYLON.VertexBuffer.UVKind
  58739. * - BABYLON.VertexBuffer.UV2Kind
  58740. * - BABYLON.VertexBuffer.UV3Kind
  58741. * - BABYLON.VertexBuffer.UV4Kind
  58742. * - BABYLON.VertexBuffer.UV5Kind
  58743. * - BABYLON.VertexBuffer.UV6Kind
  58744. * - BABYLON.VertexBuffer.ColorKind
  58745. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58746. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58747. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58748. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58749. *
  58750. * Returns the Mesh.
  58751. */
  58752. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58753. if (this.sourceMesh) {
  58754. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58755. }
  58756. return this.sourceMesh;
  58757. };
  58758. /**
  58759. * Sets the mesh indices.
  58760. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58761. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58762. * This method creates a new index buffer each call.
  58763. * Returns the Mesh.
  58764. */
  58765. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58766. if (totalVertices === void 0) { totalVertices = null; }
  58767. if (this.sourceMesh) {
  58768. this.sourceMesh.setIndices(indices, totalVertices);
  58769. }
  58770. return this.sourceMesh;
  58771. };
  58772. /**
  58773. * Boolean : True if the mesh owns the requested kind of data.
  58774. */
  58775. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58776. return this._sourceMesh.isVerticesDataPresent(kind);
  58777. };
  58778. /**
  58779. * Returns an array of indices (IndicesArray).
  58780. */
  58781. InstancedMesh.prototype.getIndices = function () {
  58782. return this._sourceMesh.getIndices();
  58783. };
  58784. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58785. get: function () {
  58786. return this._sourceMesh._positions;
  58787. },
  58788. enumerable: true,
  58789. configurable: true
  58790. });
  58791. /**
  58792. * Sets a new updated BoundingInfo to the mesh.
  58793. * Returns the mesh.
  58794. */
  58795. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58796. var meshBB = this._sourceMesh.getBoundingInfo();
  58797. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58798. this._updateBoundingInfo();
  58799. return this;
  58800. };
  58801. InstancedMesh.prototype._preActivate = function () {
  58802. if (this._currentLOD) {
  58803. this._currentLOD._preActivate();
  58804. }
  58805. return this;
  58806. };
  58807. InstancedMesh.prototype._activate = function (renderId) {
  58808. if (this._currentLOD) {
  58809. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58810. }
  58811. return this;
  58812. };
  58813. /**
  58814. * Returns the current associated LOD AbstractMesh.
  58815. */
  58816. InstancedMesh.prototype.getLOD = function (camera) {
  58817. if (!camera) {
  58818. return this;
  58819. }
  58820. var boundingInfo = this.getBoundingInfo();
  58821. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58822. if (this._currentLOD === this.sourceMesh) {
  58823. return this;
  58824. }
  58825. return this._currentLOD;
  58826. };
  58827. InstancedMesh.prototype._syncSubMeshes = function () {
  58828. this.releaseSubMeshes();
  58829. if (this._sourceMesh.subMeshes) {
  58830. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58831. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58832. }
  58833. }
  58834. return this;
  58835. };
  58836. InstancedMesh.prototype._generatePointsArray = function () {
  58837. return this._sourceMesh._generatePointsArray();
  58838. };
  58839. /**
  58840. * Creates a new InstancedMesh from the current mesh.
  58841. * - name (string) : the cloned mesh name
  58842. * - newParent (optional Node) : the optional Node to parent the clone to.
  58843. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58844. *
  58845. * Returns the clone.
  58846. */
  58847. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58848. var result = this._sourceMesh.createInstance(name);
  58849. // Deep copy
  58850. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58851. // Bounding info
  58852. this.refreshBoundingInfo();
  58853. // Parent
  58854. if (newParent) {
  58855. result.parent = newParent;
  58856. }
  58857. if (!doNotCloneChildren) {
  58858. // Children
  58859. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58860. var mesh = this.getScene().meshes[index];
  58861. if (mesh.parent === this) {
  58862. mesh.clone(mesh.name, result);
  58863. }
  58864. }
  58865. }
  58866. result.computeWorldMatrix(true);
  58867. return result;
  58868. };
  58869. /**
  58870. * Disposes the InstancedMesh.
  58871. * Returns nothing.
  58872. */
  58873. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58874. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58875. // Remove from mesh
  58876. var index = this._sourceMesh.instances.indexOf(this);
  58877. this._sourceMesh.instances.splice(index, 1);
  58878. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58879. };
  58880. return InstancedMesh;
  58881. }(BABYLON.AbstractMesh));
  58882. BABYLON.InstancedMesh = InstancedMesh;
  58883. })(BABYLON || (BABYLON = {}));
  58884. //# sourceMappingURL=babylon.instancedMesh.js.map
  58885. "use strict";
  58886. var BABYLON;
  58887. (function (BABYLON) {
  58888. var LinesMesh = /** @class */ (function (_super) {
  58889. __extends(LinesMesh, _super);
  58890. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58891. if (scene === void 0) { scene = null; }
  58892. if (parent === void 0) { parent = null; }
  58893. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58894. _this.useVertexColor = useVertexColor;
  58895. _this.useVertexAlpha = useVertexAlpha;
  58896. _this.color = new BABYLON.Color3(1, 1, 1);
  58897. _this.alpha = 1;
  58898. if (source) {
  58899. _this.color = source.color.clone();
  58900. _this.alpha = source.alpha;
  58901. _this.useVertexColor = source.useVertexColor;
  58902. _this.useVertexAlpha = source.useVertexAlpha;
  58903. }
  58904. _this._intersectionThreshold = 0.1;
  58905. var defines = [];
  58906. var options = {
  58907. attributes: [BABYLON.VertexBuffer.PositionKind],
  58908. uniforms: ["world", "viewProjection"],
  58909. needAlphaBlending: true,
  58910. defines: defines
  58911. };
  58912. if (useVertexAlpha === false) {
  58913. options.needAlphaBlending = false;
  58914. }
  58915. if (!useVertexColor) {
  58916. options.uniforms.push("color");
  58917. }
  58918. else {
  58919. options.defines.push("#define VERTEXCOLOR");
  58920. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58921. }
  58922. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58923. return _this;
  58924. }
  58925. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58926. /**
  58927. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58928. * This margin is expressed in world space coordinates, so its value may vary.
  58929. * Default value is 0.1
  58930. * @returns the intersection Threshold value.
  58931. */
  58932. get: function () {
  58933. return this._intersectionThreshold;
  58934. },
  58935. /**
  58936. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58937. * This margin is expressed in world space coordinates, so its value may vary.
  58938. * @param value the new threshold to apply
  58939. */
  58940. set: function (value) {
  58941. if (this._intersectionThreshold === value) {
  58942. return;
  58943. }
  58944. this._intersectionThreshold = value;
  58945. if (this.geometry) {
  58946. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58947. }
  58948. },
  58949. enumerable: true,
  58950. configurable: true
  58951. });
  58952. /**
  58953. * Returns the string "LineMesh"
  58954. */
  58955. LinesMesh.prototype.getClassName = function () {
  58956. return "LinesMesh";
  58957. };
  58958. Object.defineProperty(LinesMesh.prototype, "material", {
  58959. get: function () {
  58960. return this._colorShader;
  58961. },
  58962. set: function (value) {
  58963. // Do nothing
  58964. },
  58965. enumerable: true,
  58966. configurable: true
  58967. });
  58968. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58969. get: function () {
  58970. return false;
  58971. },
  58972. enumerable: true,
  58973. configurable: true
  58974. });
  58975. LinesMesh.prototype.createInstance = function (name) {
  58976. throw new Error("LinesMeshes do not support createInstance.");
  58977. };
  58978. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58979. if (!this._geometry) {
  58980. return this;
  58981. }
  58982. // VBOs
  58983. this._geometry._bind(this._colorShader.getEffect());
  58984. // Color
  58985. if (!this.useVertexColor) {
  58986. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58987. }
  58988. return this;
  58989. };
  58990. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58991. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58992. return this;
  58993. }
  58994. var engine = this.getScene().getEngine();
  58995. // Draw order
  58996. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58997. return this;
  58998. };
  58999. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59000. this._colorShader.dispose();
  59001. _super.prototype.dispose.call(this, doNotRecurse);
  59002. };
  59003. /**
  59004. * Returns a new LineMesh object cloned from the current one.
  59005. */
  59006. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59007. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59008. };
  59009. return LinesMesh;
  59010. }(BABYLON.Mesh));
  59011. BABYLON.LinesMesh = LinesMesh;
  59012. })(BABYLON || (BABYLON = {}));
  59013. //# sourceMappingURL=babylon.linesMesh.js.map
  59014. "use strict";
  59015. var BABYLON;
  59016. (function (BABYLON) {
  59017. /**
  59018. * Class containing static functions to help procedurally build meshes
  59019. */
  59020. var MeshBuilder = /** @class */ (function () {
  59021. function MeshBuilder() {
  59022. }
  59023. MeshBuilder.updateSideOrientation = function (orientation) {
  59024. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59025. return BABYLON.Mesh.DOUBLESIDE;
  59026. }
  59027. if (orientation === undefined || orientation === null) {
  59028. return BABYLON.Mesh.FRONTSIDE;
  59029. }
  59030. return orientation;
  59031. };
  59032. /**
  59033. * Creates a box mesh
  59034. * * The parameter `size` sets the size (float) of each box side (default 1)
  59035. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59036. * * 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)
  59037. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59038. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59039. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59040. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59041. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59042. * @param name defines the name of the mesh
  59043. * @param options defines the options used to create the mesh
  59044. * @param scene defines the hosting scene
  59045. * @returns the box mesh
  59046. */
  59047. MeshBuilder.CreateBox = function (name, options, scene) {
  59048. if (scene === void 0) { scene = null; }
  59049. var box = new BABYLON.Mesh(name, scene);
  59050. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59051. box._originalBuilderSideOrientation = options.sideOrientation;
  59052. var vertexData = BABYLON.VertexData.CreateBox(options);
  59053. vertexData.applyToMesh(box, options.updatable);
  59054. return box;
  59055. };
  59056. /**
  59057. * Creates a sphere mesh
  59058. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59059. * * 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`)
  59060. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59061. * * 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
  59062. * * 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)
  59063. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59064. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59065. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59066. * @param name defines the name of the mesh
  59067. * @param options defines the options used to create the mesh
  59068. * @param scene defines the hosting scene
  59069. * @returns the sphere mesh
  59070. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  59071. */
  59072. MeshBuilder.CreateSphere = function (name, options, scene) {
  59073. var sphere = new BABYLON.Mesh(name, scene);
  59074. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59075. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59076. var vertexData = BABYLON.VertexData.CreateSphere(options);
  59077. vertexData.applyToMesh(sphere, options.updatable);
  59078. return sphere;
  59079. };
  59080. /**
  59081. * Creates a plane polygonal mesh. By default, this is a disc
  59082. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  59083. * * 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
  59084. * * 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
  59085. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59086. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59087. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59088. * @param name defines the name of the mesh
  59089. * @param options defines the options used to create the mesh
  59090. * @param scene defines the hosting scene
  59091. * @returns the plane polygonal mesh
  59092. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  59093. */
  59094. MeshBuilder.CreateDisc = function (name, options, scene) {
  59095. if (scene === void 0) { scene = null; }
  59096. var disc = new BABYLON.Mesh(name, scene);
  59097. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59098. disc._originalBuilderSideOrientation = options.sideOrientation;
  59099. var vertexData = BABYLON.VertexData.CreateDisc(options);
  59100. vertexData.applyToMesh(disc, options.updatable);
  59101. return disc;
  59102. };
  59103. /**
  59104. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  59105. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  59106. * * 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`)
  59107. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  59108. * * 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
  59109. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59110. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59111. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59112. * @param name defines the name of the mesh
  59113. * @param options defines the options used to create the mesh
  59114. * @param scene defines the hosting scene
  59115. * @returns the icosahedron mesh
  59116. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  59117. */
  59118. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  59119. var sphere = new BABYLON.Mesh(name, scene);
  59120. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59121. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59122. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  59123. vertexData.applyToMesh(sphere, options.updatable);
  59124. return sphere;
  59125. };
  59126. ;
  59127. /**
  59128. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59129. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  59130. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  59131. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  59132. * * 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
  59133. * * 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
  59134. * * 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
  59135. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59136. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59137. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59138. * * 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
  59139. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  59140. * * 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
  59141. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  59142. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59143. * @param name defines the name of the mesh
  59144. * @param options defines the options used to create the mesh
  59145. * @param scene defines the hosting scene
  59146. * @returns the ribbon mesh
  59147. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  59148. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59149. */
  59150. MeshBuilder.CreateRibbon = function (name, options, scene) {
  59151. if (scene === void 0) { scene = null; }
  59152. var pathArray = options.pathArray;
  59153. var closeArray = options.closeArray;
  59154. var closePath = options.closePath;
  59155. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59156. var instance = options.instance;
  59157. var updatable = options.updatable;
  59158. if (instance) {
  59159. // positionFunction : ribbon case
  59160. // only pathArray and sideOrientation parameters are taken into account for positions update
  59161. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  59162. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  59163. var positionFunction = function (positions) {
  59164. var minlg = pathArray[0].length;
  59165. var i = 0;
  59166. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  59167. for (var si = 1; si <= ns; si++) {
  59168. for (var p = 0; p < pathArray.length; p++) {
  59169. var path = pathArray[p];
  59170. var l = path.length;
  59171. minlg = (minlg < l) ? minlg : l;
  59172. var j = 0;
  59173. while (j < minlg) {
  59174. positions[i] = path[j].x;
  59175. positions[i + 1] = path[j].y;
  59176. positions[i + 2] = path[j].z;
  59177. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  59178. BABYLON.Tmp.Vector3[0].x = path[j].x;
  59179. }
  59180. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  59181. BABYLON.Tmp.Vector3[1].x = path[j].x;
  59182. }
  59183. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  59184. BABYLON.Tmp.Vector3[0].y = path[j].y;
  59185. }
  59186. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  59187. BABYLON.Tmp.Vector3[1].y = path[j].y;
  59188. }
  59189. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  59190. BABYLON.Tmp.Vector3[0].z = path[j].z;
  59191. }
  59192. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  59193. BABYLON.Tmp.Vector3[1].z = path[j].z;
  59194. }
  59195. j++;
  59196. i += 3;
  59197. }
  59198. if (instance._closePath) {
  59199. positions[i] = path[0].x;
  59200. positions[i + 1] = path[0].y;
  59201. positions[i + 2] = path[0].z;
  59202. i += 3;
  59203. }
  59204. }
  59205. }
  59206. };
  59207. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59208. positionFunction(positions);
  59209. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  59210. instance._boundingInfo.update(instance._worldMatrix);
  59211. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59212. if (options.colors) {
  59213. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59214. for (var c = 0; c < options.colors.length; c++) {
  59215. colors[c * 4] = options.colors[c].r;
  59216. colors[c * 4 + 1] = options.colors[c].g;
  59217. colors[c * 4 + 2] = options.colors[c].b;
  59218. colors[c * 4 + 3] = options.colors[c].a;
  59219. }
  59220. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  59221. }
  59222. if (options.uvs) {
  59223. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59224. for (var i = 0; i < options.uvs.length; i++) {
  59225. uvs[i * 2] = options.uvs[i].x;
  59226. uvs[i * 2 + 1] = options.uvs[i].y;
  59227. }
  59228. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  59229. }
  59230. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  59231. var indices = instance.getIndices();
  59232. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59233. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  59234. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  59235. if (instance._closePath) {
  59236. var indexFirst = 0;
  59237. var indexLast = 0;
  59238. for (var p = 0; p < pathArray.length; p++) {
  59239. indexFirst = instance._idx[p] * 3;
  59240. if (p + 1 < pathArray.length) {
  59241. indexLast = (instance._idx[p + 1] - 1) * 3;
  59242. }
  59243. else {
  59244. indexLast = normals.length - 3;
  59245. }
  59246. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  59247. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  59248. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  59249. normals[indexLast] = normals[indexFirst];
  59250. normals[indexLast + 1] = normals[indexFirst + 1];
  59251. normals[indexLast + 2] = normals[indexFirst + 2];
  59252. }
  59253. }
  59254. if (!(instance.areNormalsFrozen)) {
  59255. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  59256. }
  59257. }
  59258. return instance;
  59259. }
  59260. else {
  59261. var ribbon = new BABYLON.Mesh(name, scene);
  59262. ribbon._originalBuilderSideOrientation = sideOrientation;
  59263. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  59264. if (closePath) {
  59265. ribbon._idx = vertexData._idx;
  59266. }
  59267. ribbon._closePath = closePath;
  59268. ribbon._closeArray = closeArray;
  59269. vertexData.applyToMesh(ribbon, updatable);
  59270. return ribbon;
  59271. }
  59272. };
  59273. /**
  59274. * Creates a cylinder or a cone mesh
  59275. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  59276. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  59277. * * 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.
  59278. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  59279. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  59280. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  59281. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  59282. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  59283. * * 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).
  59284. * * 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
  59285. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  59286. * * 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
  59287. * * 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.
  59288. * * If `enclose` is false, a ring surface is one element.
  59289. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  59290. * * 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
  59291. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59292. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59293. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59294. * @param name defines the name of the mesh
  59295. * @param options defines the options used to create the mesh
  59296. * @param scene defines the hosting scene
  59297. * @returns the cylinder mesh
  59298. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  59299. */
  59300. MeshBuilder.CreateCylinder = function (name, options, scene) {
  59301. var cylinder = new BABYLON.Mesh(name, scene);
  59302. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59303. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  59304. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  59305. vertexData.applyToMesh(cylinder, options.updatable);
  59306. return cylinder;
  59307. };
  59308. /**
  59309. * Creates a torus mesh
  59310. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  59311. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  59312. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  59313. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59314. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59315. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59316. * @param name defines the name of the mesh
  59317. * @param options defines the options used to create the mesh
  59318. * @param scene defines the hosting scene
  59319. * @returns the torus mesh
  59320. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  59321. */
  59322. MeshBuilder.CreateTorus = function (name, options, scene) {
  59323. var torus = new BABYLON.Mesh(name, scene);
  59324. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59325. torus._originalBuilderSideOrientation = options.sideOrientation;
  59326. var vertexData = BABYLON.VertexData.CreateTorus(options);
  59327. vertexData.applyToMesh(torus, options.updatable);
  59328. return torus;
  59329. };
  59330. /**
  59331. * Creates a torus knot mesh
  59332. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  59333. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  59334. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  59335. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  59336. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59337. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59338. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59339. * @param name defines the name of the mesh
  59340. * @param options defines the options used to create the mesh
  59341. * @param scene defines the hosting scene
  59342. * @returns the torus knot mesh
  59343. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  59344. */
  59345. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  59346. var torusKnot = new BABYLON.Mesh(name, scene);
  59347. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59348. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  59349. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  59350. vertexData.applyToMesh(torusKnot, options.updatable);
  59351. return torusKnot;
  59352. };
  59353. /**
  59354. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  59355. * * 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
  59356. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  59357. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  59358. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  59359. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  59360. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  59361. * * 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
  59362. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  59363. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59364. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  59365. * @param name defines the name of the new line system
  59366. * @param options defines the options used to create the line system
  59367. * @param scene defines the hosting scene
  59368. * @returns a new line system mesh
  59369. */
  59370. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  59371. var instance = options.instance;
  59372. var lines = options.lines;
  59373. var colors = options.colors;
  59374. if (instance) {
  59375. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59376. var vertexColor;
  59377. var lineColors;
  59378. if (colors) {
  59379. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59380. }
  59381. var i = 0;
  59382. var c = 0;
  59383. for (var l = 0; l < lines.length; l++) {
  59384. var points = lines[l];
  59385. for (var p = 0; p < points.length; p++) {
  59386. positions[i] = points[p].x;
  59387. positions[i + 1] = points[p].y;
  59388. positions[i + 2] = points[p].z;
  59389. if (colors && vertexColor) {
  59390. lineColors = colors[l];
  59391. vertexColor[c] = lineColors[p].r;
  59392. vertexColor[c + 1] = lineColors[p].g;
  59393. vertexColor[c + 2] = lineColors[p].b;
  59394. vertexColor[c + 3] = lineColors[p].a;
  59395. c += 4;
  59396. }
  59397. i += 3;
  59398. }
  59399. }
  59400. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59401. if (colors && vertexColor) {
  59402. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  59403. }
  59404. return instance;
  59405. }
  59406. // line system creation
  59407. var useVertexColor = (colors) ? true : false;
  59408. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  59409. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  59410. vertexData.applyToMesh(lineSystem, options.updatable);
  59411. return lineSystem;
  59412. };
  59413. /**
  59414. * Creates a line mesh
  59415. * 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
  59416. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  59417. * * The parameter `points` is an array successive Vector3
  59418. * * 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
  59419. * * The optional parameter `colors` is an array of successive Color4, one per line point
  59420. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  59421. * * When updating an instance, remember that only point positions can change, not the number of points
  59422. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59423. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  59424. * @param name defines the name of the new line system
  59425. * @param options defines the options used to create the line system
  59426. * @param scene defines the hosting scene
  59427. * @returns a new line mesh
  59428. */
  59429. MeshBuilder.CreateLines = function (name, options, scene) {
  59430. if (scene === void 0) { scene = null; }
  59431. var colors = (options.colors) ? [options.colors] : null;
  59432. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  59433. return lines;
  59434. };
  59435. /**
  59436. * Creates a dashed line mesh
  59437. * * 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
  59438. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  59439. * * The parameter `points` is an array successive Vector3
  59440. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  59441. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  59442. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  59443. * * 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
  59444. * * When updating an instance, remember that only point positions can change, not the number of points
  59445. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59446. * @param name defines the name of the mesh
  59447. * @param options defines the options used to create the mesh
  59448. * @param scene defines the hosting scene
  59449. * @returns the dashed line mesh
  59450. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  59451. */
  59452. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  59453. if (scene === void 0) { scene = null; }
  59454. var points = options.points;
  59455. var instance = options.instance;
  59456. var gapSize = options.gapSize || 1;
  59457. var dashSize = options.dashSize || 3;
  59458. if (instance) {
  59459. var positionFunction = function (positions) {
  59460. var curvect = BABYLON.Vector3.Zero();
  59461. var nbSeg = positions.length / 6;
  59462. var lg = 0;
  59463. var nb = 0;
  59464. var shft = 0;
  59465. var dashshft = 0;
  59466. var curshft = 0;
  59467. var p = 0;
  59468. var i = 0;
  59469. var j = 0;
  59470. for (i = 0; i < points.length - 1; i++) {
  59471. points[i + 1].subtractToRef(points[i], curvect);
  59472. lg += curvect.length();
  59473. }
  59474. shft = lg / nbSeg;
  59475. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  59476. for (i = 0; i < points.length - 1; i++) {
  59477. points[i + 1].subtractToRef(points[i], curvect);
  59478. nb = Math.floor(curvect.length() / shft);
  59479. curvect.normalize();
  59480. j = 0;
  59481. while (j < nb && p < positions.length) {
  59482. curshft = shft * j;
  59483. positions[p] = points[i].x + curshft * curvect.x;
  59484. positions[p + 1] = points[i].y + curshft * curvect.y;
  59485. positions[p + 2] = points[i].z + curshft * curvect.z;
  59486. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  59487. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  59488. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  59489. p += 6;
  59490. j++;
  59491. }
  59492. }
  59493. while (p < positions.length) {
  59494. positions[p] = points[i].x;
  59495. positions[p + 1] = points[i].y;
  59496. positions[p + 2] = points[i].z;
  59497. p += 3;
  59498. }
  59499. };
  59500. instance.updateMeshPositions(positionFunction, false);
  59501. return instance;
  59502. }
  59503. // dashed lines creation
  59504. var dashedLines = new BABYLON.LinesMesh(name, scene);
  59505. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  59506. vertexData.applyToMesh(dashedLines, options.updatable);
  59507. dashedLines.dashSize = dashSize;
  59508. dashedLines.gapSize = gapSize;
  59509. return dashedLines;
  59510. };
  59511. /**
  59512. * 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.
  59513. * * 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.
  59514. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59515. * * 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.
  59516. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  59517. * * 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
  59518. * * 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
  59519. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  59520. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59521. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59522. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59523. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59524. * @param name defines the name of the mesh
  59525. * @param options defines the options used to create the mesh
  59526. * @param scene defines the hosting scene
  59527. * @returns the extruded shape mesh
  59528. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59529. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59530. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  59531. */
  59532. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  59533. if (scene === void 0) { scene = null; }
  59534. var path = options.path;
  59535. var shape = options.shape;
  59536. var scale = options.scale || 1;
  59537. var rotation = options.rotation || 0;
  59538. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59539. var updatable = options.updatable;
  59540. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59541. var instance = options.instance || null;
  59542. var invertUV = options.invertUV || false;
  59543. 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);
  59544. };
  59545. /**
  59546. * Creates an custom extruded shape mesh.
  59547. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  59548. * * 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.
  59549. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59550. * * 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
  59551. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  59552. * * 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
  59553. * * It must returns a float value that will be the scale value applied to the shape on each path point
  59554. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  59555. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  59556. * * 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
  59557. * * 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
  59558. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  59559. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59560. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59561. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59562. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59563. * @param name defines the name of the mesh
  59564. * @param options defines the options used to create the mesh
  59565. * @param scene defines the hosting scene
  59566. * @returns the custom extruded shape mesh
  59567. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  59568. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59569. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59570. */
  59571. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  59572. var path = options.path;
  59573. var shape = options.shape;
  59574. var scaleFunction = options.scaleFunction || (function () { return 1; });
  59575. var rotationFunction = options.rotationFunction || (function () { return 0; });
  59576. var ribbonCloseArray = options.ribbonCloseArray || false;
  59577. var ribbonClosePath = options.ribbonClosePath || false;
  59578. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59579. var updatable = options.updatable;
  59580. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59581. var instance = options.instance;
  59582. var invertUV = options.invertUV || false;
  59583. 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);
  59584. };
  59585. /**
  59586. * Creates lathe mesh.
  59587. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  59588. * * 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
  59589. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  59590. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  59591. * * 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
  59592. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  59593. * * 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
  59594. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59595. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59596. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59597. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59598. * @param name defines the name of the mesh
  59599. * @param options defines the options used to create the mesh
  59600. * @param scene defines the hosting scene
  59601. * @returns the lathe mesh
  59602. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  59603. */
  59604. MeshBuilder.CreateLathe = function (name, options, scene) {
  59605. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  59606. var closed = (options.closed === undefined) ? true : options.closed;
  59607. var shape = options.shape;
  59608. var radius = options.radius || 1;
  59609. var tessellation = options.tessellation || 64;
  59610. var updatable = options.updatable;
  59611. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59612. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  59613. var pi2 = Math.PI * 2;
  59614. var paths = new Array();
  59615. var invertUV = options.invertUV || false;
  59616. var i = 0;
  59617. var p = 0;
  59618. var step = pi2 / tessellation * arc;
  59619. var rotated;
  59620. var path = new Array();
  59621. ;
  59622. for (i = 0; i <= tessellation; i++) {
  59623. var path = [];
  59624. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  59625. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  59626. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  59627. }
  59628. for (p = 0; p < shape.length; p++) {
  59629. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  59630. path.push(rotated);
  59631. }
  59632. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  59633. 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));
  59634. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  59635. }
  59636. paths.push(path);
  59637. }
  59638. // lathe ribbon
  59639. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  59640. return lathe;
  59641. };
  59642. /**
  59643. * Creates a plane mesh
  59644. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  59645. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  59646. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  59647. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59648. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59649. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59650. * @param name defines the name of the mesh
  59651. * @param options defines the options used to create the mesh
  59652. * @param scene defines the hosting scene
  59653. * @returns the plane mesh
  59654. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59655. */
  59656. MeshBuilder.CreatePlane = function (name, options, scene) {
  59657. var plane = new BABYLON.Mesh(name, scene);
  59658. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59659. plane._originalBuilderSideOrientation = options.sideOrientation;
  59660. var vertexData = BABYLON.VertexData.CreatePlane(options);
  59661. vertexData.applyToMesh(plane, options.updatable);
  59662. if (options.sourcePlane) {
  59663. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  59664. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  59665. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  59666. plane.rotate(vectorProduct, product);
  59667. }
  59668. return plane;
  59669. };
  59670. /**
  59671. * Creates a ground mesh
  59672. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  59673. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  59674. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59675. * @param name defines the name of the mesh
  59676. * @param options defines the options used to create the mesh
  59677. * @param scene defines the hosting scene
  59678. * @returns the ground mesh
  59679. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59680. */
  59681. MeshBuilder.CreateGround = function (name, options, scene) {
  59682. var ground = new BABYLON.GroundMesh(name, scene);
  59683. ground._setReady(false);
  59684. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  59685. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  59686. ground._width = options.width || 1;
  59687. ground._height = options.height || 1;
  59688. ground._maxX = ground._width / 2;
  59689. ground._maxZ = ground._height / 2;
  59690. ground._minX = -ground._maxX;
  59691. ground._minZ = -ground._maxZ;
  59692. var vertexData = BABYLON.VertexData.CreateGround(options);
  59693. vertexData.applyToMesh(ground, options.updatable);
  59694. ground._setReady(true);
  59695. return ground;
  59696. };
  59697. /**
  59698. * Creates a tiled ground mesh
  59699. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  59700. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  59701. * * 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
  59702. * * 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
  59703. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59704. * @param name defines the name of the mesh
  59705. * @param options defines the options used to create the mesh
  59706. * @param scene defines the hosting scene
  59707. * @returns the tiled ground mesh
  59708. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  59709. */
  59710. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  59711. var tiledGround = new BABYLON.Mesh(name, scene);
  59712. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  59713. vertexData.applyToMesh(tiledGround, options.updatable);
  59714. return tiledGround;
  59715. };
  59716. /**
  59717. * Creates a ground mesh from a height map
  59718. * * The parameter `url` sets the URL of the height map image resource.
  59719. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  59720. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  59721. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  59722. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  59723. * * 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.
  59724. * * 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).
  59725. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59726. * @param name defines the name of the mesh
  59727. * @param url defines the url to the height map
  59728. * @param options defines the options used to create the mesh
  59729. * @param scene defines the hosting scene
  59730. * @returns the ground mesh
  59731. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  59732. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  59733. */
  59734. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  59735. var width = options.width || 10.0;
  59736. var height = options.height || 10.0;
  59737. var subdivisions = options.subdivisions || 1 | 0;
  59738. var minHeight = options.minHeight || 0.0;
  59739. var maxHeight = options.maxHeight || 1.0;
  59740. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  59741. var updatable = options.updatable;
  59742. var onReady = options.onReady;
  59743. var ground = new BABYLON.GroundMesh(name, scene);
  59744. ground._subdivisionsX = subdivisions;
  59745. ground._subdivisionsY = subdivisions;
  59746. ground._width = width;
  59747. ground._height = height;
  59748. ground._maxX = ground._width / 2.0;
  59749. ground._maxZ = ground._height / 2.0;
  59750. ground._minX = -ground._maxX;
  59751. ground._minZ = -ground._maxZ;
  59752. ground._setReady(false);
  59753. var onload = function (img) {
  59754. // Getting height map data
  59755. var canvas = document.createElement("canvas");
  59756. var context = canvas.getContext("2d");
  59757. if (!context) {
  59758. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  59759. }
  59760. if (scene.isDisposed) {
  59761. return;
  59762. }
  59763. var bufferWidth = img.width;
  59764. var bufferHeight = img.height;
  59765. canvas.width = bufferWidth;
  59766. canvas.height = bufferHeight;
  59767. context.drawImage(img, 0, 0);
  59768. // Create VertexData from map data
  59769. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  59770. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  59771. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  59772. width: width, height: height,
  59773. subdivisions: subdivisions,
  59774. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  59775. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  59776. });
  59777. vertexData.applyToMesh(ground, updatable);
  59778. //execute ready callback, if set
  59779. if (onReady) {
  59780. onReady(ground);
  59781. }
  59782. ground._setReady(true);
  59783. };
  59784. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  59785. return ground;
  59786. };
  59787. /**
  59788. * Creates a polygon mesh
  59789. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  59790. * * 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
  59791. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59792. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59793. * * 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)
  59794. * * Remember you can only change the shape positions, not their number when updating a polygon
  59795. * @param name defines the name of the mesh
  59796. * @param options defines the options used to create the mesh
  59797. * @param scene defines the hosting scene
  59798. * @returns the polygon mesh
  59799. */
  59800. MeshBuilder.CreatePolygon = function (name, options, scene) {
  59801. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59802. var shape = options.shape;
  59803. var holes = options.holes || [];
  59804. var depth = options.depth || 0;
  59805. var contours = [];
  59806. var hole = [];
  59807. for (var i = 0; i < shape.length; i++) {
  59808. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  59809. }
  59810. var epsilon = 0.00000001;
  59811. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  59812. contours.pop();
  59813. }
  59814. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  59815. for (var hNb = 0; hNb < holes.length; hNb++) {
  59816. hole = [];
  59817. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  59818. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  59819. }
  59820. polygonTriangulation.addHole(hole);
  59821. }
  59822. var polygon = polygonTriangulation.build(options.updatable, depth);
  59823. polygon._originalBuilderSideOrientation = options.sideOrientation;
  59824. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  59825. vertexData.applyToMesh(polygon, options.updatable);
  59826. return polygon;
  59827. };
  59828. ;
  59829. /**
  59830. * Creates an extruded polygon mesh, with depth in the Y direction.
  59831. * * 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)
  59832. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59833. * @param name defines the name of the mesh
  59834. * @param options defines the options used to create the mesh
  59835. * @param scene defines the hosting scene
  59836. * @returns the polygon mesh
  59837. */
  59838. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  59839. return MeshBuilder.CreatePolygon(name, options, scene);
  59840. };
  59841. ;
  59842. /**
  59843. * Creates a tube mesh.
  59844. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59845. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  59846. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  59847. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  59848. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  59849. * * 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)
  59850. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  59851. * * 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
  59852. * * 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
  59853. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59854. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59855. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59856. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59857. * @param name defines the name of the mesh
  59858. * @param options defines the options used to create the mesh
  59859. * @param scene defines the hosting scene
  59860. * @returns the tube mesh
  59861. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59862. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  59863. */
  59864. MeshBuilder.CreateTube = function (name, options, scene) {
  59865. var path = options.path;
  59866. var instance = options.instance;
  59867. var radius = 1.0;
  59868. if (instance) {
  59869. radius = instance.radius;
  59870. }
  59871. if (options.radius !== undefined) {
  59872. radius = options.radius;
  59873. }
  59874. ;
  59875. var tessellation = options.tessellation || 64 | 0;
  59876. var radiusFunction = options.radiusFunction || null;
  59877. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  59878. var invertUV = options.invertUV || false;
  59879. var updatable = options.updatable;
  59880. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59881. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  59882. // tube geometry
  59883. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  59884. var tangents = path3D.getTangents();
  59885. var normals = path3D.getNormals();
  59886. var distances = path3D.getDistances();
  59887. var pi2 = Math.PI * 2;
  59888. var step = pi2 / tessellation * arc;
  59889. var returnRadius = function () { return radius; };
  59890. var radiusFunctionFinal = radiusFunction || returnRadius;
  59891. var circlePath;
  59892. var rad;
  59893. var normal;
  59894. var rotated;
  59895. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  59896. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  59897. for (var i = 0; i < path.length; i++) {
  59898. rad = radiusFunctionFinal(i, distances[i]); // current radius
  59899. circlePath = Array(); // current circle array
  59900. normal = normals[i]; // current normal
  59901. for (var t = 0; t < tessellation; t++) {
  59902. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  59903. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  59904. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  59905. rotated.scaleInPlace(rad).addInPlace(path[i]);
  59906. circlePath[t] = rotated;
  59907. }
  59908. circlePaths[index] = circlePath;
  59909. index++;
  59910. }
  59911. // cap
  59912. var capPath = function (nbPoints, pathIndex) {
  59913. var pointCap = Array();
  59914. for (var i = 0; i < nbPoints; i++) {
  59915. pointCap.push(path[pathIndex]);
  59916. }
  59917. return pointCap;
  59918. };
  59919. switch (cap) {
  59920. case BABYLON.Mesh.NO_CAP:
  59921. break;
  59922. case BABYLON.Mesh.CAP_START:
  59923. circlePaths[0] = capPath(tessellation, 0);
  59924. circlePaths[1] = circlePaths[2].slice(0);
  59925. break;
  59926. case BABYLON.Mesh.CAP_END:
  59927. circlePaths[index] = circlePaths[index - 1].slice(0);
  59928. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  59929. break;
  59930. case BABYLON.Mesh.CAP_ALL:
  59931. circlePaths[0] = capPath(tessellation, 0);
  59932. circlePaths[1] = circlePaths[2].slice(0);
  59933. circlePaths[index] = circlePaths[index - 1].slice(0);
  59934. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  59935. break;
  59936. default:
  59937. break;
  59938. }
  59939. return circlePaths;
  59940. };
  59941. var path3D;
  59942. var pathArray;
  59943. if (instance) {
  59944. var arc = options.arc || instance.arc;
  59945. path3D = (instance.path3D).update(path);
  59946. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  59947. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  59948. instance.path3D = path3D;
  59949. instance.pathArray = pathArray;
  59950. instance.arc = arc;
  59951. instance.radius = radius;
  59952. return instance;
  59953. }
  59954. // tube creation
  59955. path3D = new BABYLON.Path3D(path);
  59956. var newPathArray = new Array();
  59957. cap = (cap < 0 || cap > 3) ? 0 : cap;
  59958. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  59959. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  59960. tube.pathArray = pathArray;
  59961. tube.path3D = path3D;
  59962. tube.tessellation = tessellation;
  59963. tube.cap = cap;
  59964. tube.arc = options.arc;
  59965. tube.radius = radius;
  59966. return tube;
  59967. };
  59968. /**
  59969. * Creates a polyhedron mesh
  59970. * * 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
  59971. * * The parameter `size` (positive float, default 1) sets the polygon size
  59972. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  59973. * * 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`
  59974. * * 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
  59975. * * 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)`)
  59976. * * 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
  59977. * * 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
  59978. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59979. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59980. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59981. * @param name defines the name of the mesh
  59982. * @param options defines the options used to create the mesh
  59983. * @param scene defines the hosting scene
  59984. * @returns the polyhedron mesh
  59985. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  59986. */
  59987. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  59988. var polyhedron = new BABYLON.Mesh(name, scene);
  59989. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59990. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  59991. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  59992. vertexData.applyToMesh(polyhedron, options.updatable);
  59993. return polyhedron;
  59994. };
  59995. /**
  59996. * Creates a decal mesh.
  59997. * 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
  59998. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  59999. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60000. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60001. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60002. * @param name defines the name of the mesh
  60003. * @param sourceMesh defines the mesh where the decal must be applied
  60004. * @param options defines the options used to create the mesh
  60005. * @param scene defines the hosting scene
  60006. * @returns the decal mesh
  60007. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  60008. */
  60009. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60010. var indices = sourceMesh.getIndices();
  60011. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60012. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60013. var position = options.position || BABYLON.Vector3.Zero();
  60014. var normal = options.normal || BABYLON.Vector3.Up();
  60015. var size = options.size || BABYLON.Vector3.One();
  60016. var angle = options.angle || 0;
  60017. // Getting correct rotation
  60018. if (!normal) {
  60019. var target = new BABYLON.Vector3(0, 0, 1);
  60020. var camera = sourceMesh.getScene().activeCamera;
  60021. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60022. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60023. }
  60024. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60025. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60026. var pitch = Math.atan2(normal.y, len);
  60027. // Matrix
  60028. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60029. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60030. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60031. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60032. var vertexData = new BABYLON.VertexData();
  60033. vertexData.indices = [];
  60034. vertexData.positions = [];
  60035. vertexData.normals = [];
  60036. vertexData.uvs = [];
  60037. var currentVertexDataIndex = 0;
  60038. var extractDecalVector3 = function (indexId) {
  60039. var result = new BABYLON.PositionNormalVertex();
  60040. if (!indices || !positions || !normals) {
  60041. return result;
  60042. }
  60043. var vertexId = indices[indexId];
  60044. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60045. // Send vector to decal local world
  60046. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60047. // Get normal
  60048. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60049. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60050. return result;
  60051. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60052. var clip = function (vertices, axis) {
  60053. if (vertices.length === 0) {
  60054. return vertices;
  60055. }
  60056. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60057. var clipVertices = function (v0, v1) {
  60058. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60059. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60060. };
  60061. var result = new Array();
  60062. for (var index = 0; index < vertices.length; index += 3) {
  60063. var v1Out;
  60064. var v2Out;
  60065. var v3Out;
  60066. var total = 0;
  60067. var nV1 = null;
  60068. var nV2 = null;
  60069. var nV3 = null;
  60070. var nV4 = null;
  60071. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  60072. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  60073. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  60074. v1Out = d1 > 0;
  60075. v2Out = d2 > 0;
  60076. v3Out = d3 > 0;
  60077. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  60078. switch (total) {
  60079. case 0:
  60080. result.push(vertices[index]);
  60081. result.push(vertices[index + 1]);
  60082. result.push(vertices[index + 2]);
  60083. break;
  60084. case 1:
  60085. if (v1Out) {
  60086. nV1 = vertices[index + 1];
  60087. nV2 = vertices[index + 2];
  60088. nV3 = clipVertices(vertices[index], nV1);
  60089. nV4 = clipVertices(vertices[index], nV2);
  60090. }
  60091. if (v2Out) {
  60092. nV1 = vertices[index];
  60093. nV2 = vertices[index + 2];
  60094. nV3 = clipVertices(vertices[index + 1], nV1);
  60095. nV4 = clipVertices(vertices[index + 1], nV2);
  60096. result.push(nV3);
  60097. result.push(nV2.clone());
  60098. result.push(nV1.clone());
  60099. result.push(nV2.clone());
  60100. result.push(nV3.clone());
  60101. result.push(nV4);
  60102. break;
  60103. }
  60104. if (v3Out) {
  60105. nV1 = vertices[index];
  60106. nV2 = vertices[index + 1];
  60107. nV3 = clipVertices(vertices[index + 2], nV1);
  60108. nV4 = clipVertices(vertices[index + 2], nV2);
  60109. }
  60110. if (nV1 && nV2 && nV3 && nV4) {
  60111. result.push(nV1.clone());
  60112. result.push(nV2.clone());
  60113. result.push(nV3);
  60114. result.push(nV4);
  60115. result.push(nV3.clone());
  60116. result.push(nV2.clone());
  60117. }
  60118. break;
  60119. case 2:
  60120. if (!v1Out) {
  60121. nV1 = vertices[index].clone();
  60122. nV2 = clipVertices(nV1, vertices[index + 1]);
  60123. nV3 = clipVertices(nV1, vertices[index + 2]);
  60124. result.push(nV1);
  60125. result.push(nV2);
  60126. result.push(nV3);
  60127. }
  60128. if (!v2Out) {
  60129. nV1 = vertices[index + 1].clone();
  60130. nV2 = clipVertices(nV1, vertices[index + 2]);
  60131. nV3 = clipVertices(nV1, vertices[index]);
  60132. result.push(nV1);
  60133. result.push(nV2);
  60134. result.push(nV3);
  60135. }
  60136. if (!v3Out) {
  60137. nV1 = vertices[index + 2].clone();
  60138. nV2 = clipVertices(nV1, vertices[index]);
  60139. nV3 = clipVertices(nV1, vertices[index + 1]);
  60140. result.push(nV1);
  60141. result.push(nV2);
  60142. result.push(nV3);
  60143. }
  60144. break;
  60145. case 3:
  60146. break;
  60147. }
  60148. }
  60149. return result;
  60150. };
  60151. for (var index = 0; index < indices.length; index += 3) {
  60152. var faceVertices = new Array();
  60153. faceVertices.push(extractDecalVector3(index));
  60154. faceVertices.push(extractDecalVector3(index + 1));
  60155. faceVertices.push(extractDecalVector3(index + 2));
  60156. // Clip
  60157. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  60158. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  60159. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  60160. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  60161. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  60162. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  60163. if (faceVertices.length === 0) {
  60164. continue;
  60165. }
  60166. // Add UVs and get back to world
  60167. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  60168. var vertex = faceVertices[vIndex];
  60169. //TODO check for Int32Array | Uint32Array | Uint16Array
  60170. vertexData.indices.push(currentVertexDataIndex);
  60171. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  60172. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  60173. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  60174. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  60175. currentVertexDataIndex++;
  60176. }
  60177. }
  60178. // Return mesh
  60179. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  60180. vertexData.applyToMesh(decal);
  60181. decal.position = position.clone();
  60182. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  60183. return decal;
  60184. };
  60185. // Privates
  60186. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  60187. // extrusion geometry
  60188. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  60189. var tangents = path3D.getTangents();
  60190. var normals = path3D.getNormals();
  60191. var binormals = path3D.getBinormals();
  60192. var distances = path3D.getDistances();
  60193. var angle = 0;
  60194. var returnScale = function () { return scale !== null ? scale : 1; };
  60195. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  60196. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  60197. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  60198. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60199. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60200. for (var i = 0; i < curve.length; i++) {
  60201. var shapePath = new Array();
  60202. var angleStep = rotate(i, distances[i]);
  60203. var scaleRatio = scl(i, distances[i]);
  60204. for (var p = 0; p < shape.length; p++) {
  60205. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  60206. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  60207. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  60208. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  60209. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  60210. shapePath[p] = rotated;
  60211. }
  60212. shapePaths[index] = shapePath;
  60213. angle += angleStep;
  60214. index++;
  60215. }
  60216. // cap
  60217. var capPath = function (shapePath) {
  60218. var pointCap = Array();
  60219. var barycenter = BABYLON.Vector3.Zero();
  60220. var i;
  60221. for (i = 0; i < shapePath.length; i++) {
  60222. barycenter.addInPlace(shapePath[i]);
  60223. }
  60224. barycenter.scaleInPlace(1.0 / shapePath.length);
  60225. for (i = 0; i < shapePath.length; i++) {
  60226. pointCap.push(barycenter);
  60227. }
  60228. return pointCap;
  60229. };
  60230. switch (cap) {
  60231. case BABYLON.Mesh.NO_CAP:
  60232. break;
  60233. case BABYLON.Mesh.CAP_START:
  60234. shapePaths[0] = capPath(shapePaths[2]);
  60235. shapePaths[1] = shapePaths[2];
  60236. break;
  60237. case BABYLON.Mesh.CAP_END:
  60238. shapePaths[index] = shapePaths[index - 1];
  60239. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60240. break;
  60241. case BABYLON.Mesh.CAP_ALL:
  60242. shapePaths[0] = capPath(shapePaths[2]);
  60243. shapePaths[1] = shapePaths[2];
  60244. shapePaths[index] = shapePaths[index - 1];
  60245. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60246. break;
  60247. default:
  60248. break;
  60249. }
  60250. return shapePaths;
  60251. };
  60252. var path3D;
  60253. var pathArray;
  60254. if (instance) {
  60255. path3D = (instance.path3D).update(curve);
  60256. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  60257. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  60258. return instance;
  60259. }
  60260. // extruded shape creation
  60261. path3D = new BABYLON.Path3D(curve);
  60262. var newShapePaths = new Array();
  60263. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60264. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  60265. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  60266. extrudedGeneric.pathArray = pathArray;
  60267. extrudedGeneric.path3D = path3D;
  60268. extrudedGeneric.cap = cap;
  60269. return extrudedGeneric;
  60270. };
  60271. return MeshBuilder;
  60272. }());
  60273. BABYLON.MeshBuilder = MeshBuilder;
  60274. })(BABYLON || (BABYLON = {}));
  60275. //# sourceMappingURL=babylon.meshBuilder.js.map
  60276. "use strict";
  60277. var BABYLON;
  60278. (function (BABYLON) {
  60279. /**
  60280. * Draco compression (https://google.github.io/draco/)
  60281. */
  60282. var DracoCompression = /** @class */ (function () {
  60283. /**
  60284. * Constructor
  60285. * @param numWorkers The number of workers for async operations
  60286. */
  60287. function DracoCompression(numWorkers) {
  60288. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  60289. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  60290. if (!workerBlobUrl || !Worker) {
  60291. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  60292. return;
  60293. }
  60294. var workers = new Array(numWorkers);
  60295. for (var i = 0; i < workers.length; i++) {
  60296. var worker = new Worker(workerBlobUrl);
  60297. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  60298. workers[i] = worker;
  60299. }
  60300. this._workerPool = new BABYLON.WorkerPool(workers);
  60301. }
  60302. /**
  60303. * Stop all async operations and release resources.
  60304. */
  60305. DracoCompression.prototype.dispose = function () {
  60306. this._workerPool.dispose();
  60307. delete this._workerPool;
  60308. };
  60309. /**
  60310. * Decode Draco compressed mesh data to vertex data.
  60311. * @param data The array buffer view for the Draco compression data
  60312. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  60313. * @returns A promise that resolves with the decoded vertex data
  60314. */
  60315. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  60316. var _this = this;
  60317. return new Promise(function (resolve, reject) {
  60318. _this._workerPool.push(function (worker, onComplete) {
  60319. var vertexData = new BABYLON.VertexData();
  60320. var onError = function (error) {
  60321. worker.removeEventListener("error", onError);
  60322. worker.removeEventListener("message", onMessage);
  60323. reject(error);
  60324. onComplete();
  60325. };
  60326. var onMessage = function (message) {
  60327. if (message.data === "done") {
  60328. worker.removeEventListener("error", onError);
  60329. worker.removeEventListener("message", onMessage);
  60330. resolve(vertexData);
  60331. onComplete();
  60332. }
  60333. else if (message.data.id === "indices") {
  60334. vertexData.indices = message.data.value;
  60335. }
  60336. else {
  60337. vertexData.set(message.data.value, message.data.id);
  60338. }
  60339. };
  60340. worker.addEventListener("error", onError);
  60341. worker.addEventListener("message", onMessage);
  60342. var dataCopy = new Uint8Array(data.byteLength);
  60343. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  60344. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  60345. });
  60346. });
  60347. };
  60348. /**
  60349. * The worker function that gets converted to a blob url to pass into a worker.
  60350. */
  60351. DracoCompression._Worker = function () {
  60352. // self is actually a DedicatedWorkerGlobalScope
  60353. var _self = self;
  60354. var decodeMesh = function (data, attributes) {
  60355. var dracoModule = new DracoDecoderModule();
  60356. var buffer = new dracoModule.DecoderBuffer();
  60357. buffer.Init(data, data.byteLength);
  60358. var decoder = new dracoModule.Decoder();
  60359. var geometry;
  60360. var status;
  60361. try {
  60362. var type = decoder.GetEncodedGeometryType(buffer);
  60363. switch (type) {
  60364. case dracoModule.TRIANGULAR_MESH:
  60365. geometry = new dracoModule.Mesh();
  60366. status = decoder.DecodeBufferToMesh(buffer, geometry);
  60367. break;
  60368. case dracoModule.POINT_CLOUD:
  60369. geometry = new dracoModule.PointCloud();
  60370. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  60371. break;
  60372. default:
  60373. throw new Error("Invalid geometry type " + type);
  60374. }
  60375. if (!status.ok() || !geometry.ptr) {
  60376. throw new Error(status.error_msg());
  60377. }
  60378. var numPoints = geometry.num_points();
  60379. if (type === dracoModule.TRIANGULAR_MESH) {
  60380. var numFaces = geometry.num_faces();
  60381. var faceIndices = new dracoModule.DracoInt32Array();
  60382. try {
  60383. var indices = new Uint32Array(numFaces * 3);
  60384. for (var i = 0; i < numFaces; i++) {
  60385. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  60386. var offset = i * 3;
  60387. indices[offset + 0] = faceIndices.GetValue(0);
  60388. indices[offset + 1] = faceIndices.GetValue(1);
  60389. indices[offset + 2] = faceIndices.GetValue(2);
  60390. }
  60391. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  60392. }
  60393. finally {
  60394. dracoModule.destroy(faceIndices);
  60395. }
  60396. }
  60397. for (var kind in attributes) {
  60398. var uniqueId = attributes[kind];
  60399. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  60400. var dracoData = new dracoModule.DracoFloat32Array();
  60401. try {
  60402. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  60403. var babylonData = new Float32Array(numPoints * attribute.num_components());
  60404. for (var i = 0; i < babylonData.length; i++) {
  60405. babylonData[i] = dracoData.GetValue(i);
  60406. }
  60407. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  60408. }
  60409. finally {
  60410. dracoModule.destroy(dracoData);
  60411. }
  60412. }
  60413. }
  60414. finally {
  60415. if (geometry) {
  60416. dracoModule.destroy(geometry);
  60417. }
  60418. dracoModule.destroy(decoder);
  60419. dracoModule.destroy(buffer);
  60420. }
  60421. _self.postMessage("done");
  60422. };
  60423. _self.onmessage = function (event) {
  60424. switch (event.data.id) {
  60425. case "initDecoder": {
  60426. importScripts(event.data.url);
  60427. break;
  60428. }
  60429. case "decodeMesh": {
  60430. decodeMesh(event.data.data, event.data.attributes);
  60431. break;
  60432. }
  60433. }
  60434. };
  60435. };
  60436. DracoCompression._GetDefaultDecoderUrl = function () {
  60437. if (!BABYLON.Tools.IsWindowObjectExist()) {
  60438. return null;
  60439. }
  60440. for (var i = 0; i < document.scripts.length; i++) {
  60441. if (document.scripts[i].type === "text/x-draco-decoder") {
  60442. return document.scripts[i].src;
  60443. }
  60444. }
  60445. return null;
  60446. };
  60447. /**
  60448. * Gets the url to the draco decoder if available.
  60449. */
  60450. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  60451. return DracoCompression;
  60452. }());
  60453. BABYLON.DracoCompression = DracoCompression;
  60454. })(BABYLON || (BABYLON = {}));
  60455. //# sourceMappingURL=babylon.dracoCompression.js.map
  60456. "use strict";
  60457. var BABYLON;
  60458. (function (BABYLON) {
  60459. var AudioEngine = /** @class */ (function () {
  60460. function AudioEngine() {
  60461. this._audioContext = null;
  60462. this._audioContextInitialized = false;
  60463. this.canUseWebAudio = false;
  60464. this.WarnedWebAudioUnsupported = false;
  60465. this.unlocked = false;
  60466. this.isMP3supported = false;
  60467. this.isOGGsupported = false;
  60468. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  60469. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  60470. this.canUseWebAudio = true;
  60471. }
  60472. var audioElem = document.createElement('audio');
  60473. try {
  60474. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  60475. this.isMP3supported = true;
  60476. }
  60477. }
  60478. catch (e) {
  60479. // protect error during capability check.
  60480. }
  60481. try {
  60482. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  60483. this.isOGGsupported = true;
  60484. }
  60485. }
  60486. catch (e) {
  60487. // protect error during capability check.
  60488. }
  60489. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  60490. this._unlockiOSaudio();
  60491. }
  60492. else {
  60493. this.unlocked = true;
  60494. }
  60495. }
  60496. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  60497. get: function () {
  60498. if (!this._audioContextInitialized) {
  60499. this._initializeAudioContext();
  60500. }
  60501. return this._audioContext;
  60502. },
  60503. enumerable: true,
  60504. configurable: true
  60505. });
  60506. AudioEngine.prototype._unlockiOSaudio = function () {
  60507. var _this = this;
  60508. var unlockaudio = function () {
  60509. if (!_this.audioContext) {
  60510. return;
  60511. }
  60512. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  60513. var source = _this.audioContext.createBufferSource();
  60514. source.buffer = buffer;
  60515. source.connect(_this.audioContext.destination);
  60516. source.start(0);
  60517. setTimeout(function () {
  60518. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  60519. _this.unlocked = true;
  60520. window.removeEventListener('touchend', unlockaudio, false);
  60521. if (_this.onAudioUnlocked) {
  60522. _this.onAudioUnlocked();
  60523. }
  60524. }
  60525. }, 0);
  60526. };
  60527. window.addEventListener('touchend', unlockaudio, false);
  60528. };
  60529. AudioEngine.prototype._initializeAudioContext = function () {
  60530. try {
  60531. if (this.canUseWebAudio) {
  60532. this._audioContext = new AudioContext();
  60533. // create a global volume gain node
  60534. this.masterGain = this._audioContext.createGain();
  60535. this.masterGain.gain.value = 1;
  60536. this.masterGain.connect(this._audioContext.destination);
  60537. this._audioContextInitialized = true;
  60538. }
  60539. }
  60540. catch (e) {
  60541. this.canUseWebAudio = false;
  60542. BABYLON.Tools.Error("Web Audio: " + e.message);
  60543. }
  60544. };
  60545. AudioEngine.prototype.dispose = function () {
  60546. if (this.canUseWebAudio && this._audioContextInitialized) {
  60547. if (this._connectedAnalyser && this._audioContext) {
  60548. this._connectedAnalyser.stopDebugCanvas();
  60549. this._connectedAnalyser.dispose();
  60550. this.masterGain.disconnect();
  60551. this.masterGain.connect(this._audioContext.destination);
  60552. this._connectedAnalyser = null;
  60553. }
  60554. this.masterGain.gain.value = 1;
  60555. }
  60556. this.WarnedWebAudioUnsupported = false;
  60557. };
  60558. AudioEngine.prototype.getGlobalVolume = function () {
  60559. if (this.canUseWebAudio && this._audioContextInitialized) {
  60560. return this.masterGain.gain.value;
  60561. }
  60562. else {
  60563. return -1;
  60564. }
  60565. };
  60566. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  60567. if (this.canUseWebAudio && this._audioContextInitialized) {
  60568. this.masterGain.gain.value = newVolume;
  60569. }
  60570. };
  60571. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  60572. if (this._connectedAnalyser) {
  60573. this._connectedAnalyser.stopDebugCanvas();
  60574. }
  60575. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  60576. this._connectedAnalyser = analyser;
  60577. this.masterGain.disconnect();
  60578. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  60579. }
  60580. };
  60581. return AudioEngine;
  60582. }());
  60583. BABYLON.AudioEngine = AudioEngine;
  60584. })(BABYLON || (BABYLON = {}));
  60585. //# sourceMappingURL=babylon.audioEngine.js.map
  60586. "use strict";
  60587. var BABYLON;
  60588. (function (BABYLON) {
  60589. var Sound = /** @class */ (function () {
  60590. /**
  60591. * Create a sound and attach it to a scene
  60592. * @param name Name of your sound
  60593. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  60594. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  60595. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  60596. */
  60597. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  60598. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  60599. var _this = this;
  60600. this.autoplay = false;
  60601. this.loop = false;
  60602. this.useCustomAttenuation = false;
  60603. this.spatialSound = false;
  60604. this.refDistance = 1;
  60605. this.rolloffFactor = 1;
  60606. this.maxDistance = 100;
  60607. this.distanceModel = "linear";
  60608. this._panningModel = "equalpower";
  60609. this._playbackRate = 1;
  60610. this._streaming = false;
  60611. this._startTime = 0;
  60612. this._startOffset = 0;
  60613. this._position = BABYLON.Vector3.Zero();
  60614. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  60615. this._volume = 1;
  60616. this._isReadyToPlay = false;
  60617. this.isPlaying = false;
  60618. this.isPaused = false;
  60619. this._isDirectional = false;
  60620. // Used if you'd like to create a directional sound.
  60621. // If not set, the sound will be omnidirectional
  60622. this._coneInnerAngle = 360;
  60623. this._coneOuterAngle = 360;
  60624. this._coneOuterGain = 0;
  60625. this._isOutputConnected = false;
  60626. this._urlType = "Unknown";
  60627. this.name = name;
  60628. this._scene = scene;
  60629. this._readyToPlayCallback = readyToPlayCallback;
  60630. // Default custom attenuation function is a linear attenuation
  60631. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  60632. if (currentDistance < maxDistance) {
  60633. return currentVolume * (1 - currentDistance / maxDistance);
  60634. }
  60635. else {
  60636. return 0;
  60637. }
  60638. };
  60639. if (options) {
  60640. this.autoplay = options.autoplay || false;
  60641. this.loop = options.loop || false;
  60642. // if volume === 0, we need another way to check this option
  60643. if (options.volume !== undefined) {
  60644. this._volume = options.volume;
  60645. }
  60646. this.spatialSound = options.spatialSound || false;
  60647. this.maxDistance = options.maxDistance || 100;
  60648. this.useCustomAttenuation = options.useCustomAttenuation || false;
  60649. this.rolloffFactor = options.rolloffFactor || 1;
  60650. this.refDistance = options.refDistance || 1;
  60651. this.distanceModel = options.distanceModel || "linear";
  60652. this._playbackRate = options.playbackRate || 1;
  60653. this._streaming = options.streaming || false;
  60654. }
  60655. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60656. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  60657. this._soundGain.gain.value = this._volume;
  60658. this._inputAudioNode = this._soundGain;
  60659. this._ouputAudioNode = this._soundGain;
  60660. if (this.spatialSound) {
  60661. this._createSpatialParameters();
  60662. }
  60663. this._scene.mainSoundTrack.AddSound(this);
  60664. var validParameter = true;
  60665. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  60666. if (urlOrArrayBuffer) {
  60667. try {
  60668. if (typeof (urlOrArrayBuffer) === "string")
  60669. this._urlType = "String";
  60670. if (Array.isArray(urlOrArrayBuffer))
  60671. this._urlType = "Array";
  60672. if (urlOrArrayBuffer instanceof ArrayBuffer)
  60673. this._urlType = "ArrayBuffer";
  60674. var urls = [];
  60675. var codecSupportedFound = false;
  60676. switch (this._urlType) {
  60677. case "ArrayBuffer":
  60678. if (urlOrArrayBuffer.byteLength > 0) {
  60679. codecSupportedFound = true;
  60680. this._soundLoaded(urlOrArrayBuffer);
  60681. }
  60682. break;
  60683. case "String":
  60684. urls.push(urlOrArrayBuffer);
  60685. case "Array":
  60686. if (urls.length === 0)
  60687. urls = urlOrArrayBuffer;
  60688. // If we found a supported format, we load it immediately and stop the loop
  60689. for (var i = 0; i < urls.length; i++) {
  60690. var url = urls[i];
  60691. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  60692. codecSupportedFound = true;
  60693. }
  60694. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  60695. codecSupportedFound = true;
  60696. }
  60697. if (url.indexOf(".wav", url.length - 4) !== -1) {
  60698. codecSupportedFound = true;
  60699. }
  60700. if (url.indexOf("blob:") !== -1) {
  60701. codecSupportedFound = true;
  60702. }
  60703. if (codecSupportedFound) {
  60704. // Loading sound using XHR2
  60705. if (!this._streaming) {
  60706. this._scene._loadFile(url, function (data) {
  60707. _this._soundLoaded(data);
  60708. }, undefined, true, true, function (exception) {
  60709. if (exception) {
  60710. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  60711. }
  60712. BABYLON.Tools.Error("Sound creation aborted.");
  60713. _this._scene.mainSoundTrack.RemoveSound(_this);
  60714. });
  60715. }
  60716. else {
  60717. this._htmlAudioElement = new Audio(url);
  60718. this._htmlAudioElement.controls = false;
  60719. this._htmlAudioElement.loop = this.loop;
  60720. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  60721. this._htmlAudioElement.preload = "auto";
  60722. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  60723. _this._isReadyToPlay = true;
  60724. if (_this.autoplay) {
  60725. _this.play();
  60726. }
  60727. if (_this._readyToPlayCallback) {
  60728. _this._readyToPlayCallback();
  60729. }
  60730. });
  60731. document.body.appendChild(this._htmlAudioElement);
  60732. }
  60733. break;
  60734. }
  60735. }
  60736. break;
  60737. default:
  60738. validParameter = false;
  60739. break;
  60740. }
  60741. if (!validParameter) {
  60742. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  60743. }
  60744. else {
  60745. if (!codecSupportedFound) {
  60746. this._isReadyToPlay = true;
  60747. // Simulating a ready to play event to avoid breaking code path
  60748. if (this._readyToPlayCallback) {
  60749. window.setTimeout(function () {
  60750. if (_this._readyToPlayCallback) {
  60751. _this._readyToPlayCallback();
  60752. }
  60753. }, 1000);
  60754. }
  60755. }
  60756. }
  60757. }
  60758. catch (ex) {
  60759. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  60760. this._scene.mainSoundTrack.RemoveSound(this);
  60761. }
  60762. }
  60763. }
  60764. else {
  60765. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  60766. this._scene.mainSoundTrack.AddSound(this);
  60767. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  60768. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  60769. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  60770. }
  60771. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  60772. if (this._readyToPlayCallback) {
  60773. window.setTimeout(function () {
  60774. if (_this._readyToPlayCallback) {
  60775. _this._readyToPlayCallback();
  60776. }
  60777. }, 1000);
  60778. }
  60779. }
  60780. }
  60781. Sound.prototype.dispose = function () {
  60782. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60783. if (this.isPlaying) {
  60784. this.stop();
  60785. }
  60786. this._isReadyToPlay = false;
  60787. if (this.soundTrackId === -1) {
  60788. this._scene.mainSoundTrack.RemoveSound(this);
  60789. }
  60790. else {
  60791. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  60792. }
  60793. if (this._soundGain) {
  60794. this._soundGain.disconnect();
  60795. this._soundGain = null;
  60796. }
  60797. if (this._soundPanner) {
  60798. this._soundPanner.disconnect();
  60799. this._soundPanner = null;
  60800. }
  60801. if (this._soundSource) {
  60802. this._soundSource.disconnect();
  60803. this._soundSource = null;
  60804. }
  60805. this._audioBuffer = null;
  60806. if (this._htmlAudioElement) {
  60807. this._htmlAudioElement.pause();
  60808. this._htmlAudioElement.src = "";
  60809. document.body.removeChild(this._htmlAudioElement);
  60810. }
  60811. if (this._connectedMesh && this._registerFunc) {
  60812. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  60813. this._connectedMesh = null;
  60814. }
  60815. }
  60816. };
  60817. Sound.prototype.isReady = function () {
  60818. return this._isReadyToPlay;
  60819. };
  60820. Sound.prototype._soundLoaded = function (audioData) {
  60821. var _this = this;
  60822. if (!BABYLON.Engine.audioEngine.audioContext) {
  60823. return;
  60824. }
  60825. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  60826. _this._audioBuffer = buffer;
  60827. _this._isReadyToPlay = true;
  60828. if (_this.autoplay) {
  60829. _this.play();
  60830. }
  60831. if (_this._readyToPlayCallback) {
  60832. _this._readyToPlayCallback();
  60833. }
  60834. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  60835. };
  60836. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  60837. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60838. this._audioBuffer = audioBuffer;
  60839. this._isReadyToPlay = true;
  60840. }
  60841. };
  60842. Sound.prototype.updateOptions = function (options) {
  60843. if (options) {
  60844. this.loop = options.loop || this.loop;
  60845. this.maxDistance = options.maxDistance || this.maxDistance;
  60846. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  60847. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  60848. this.refDistance = options.refDistance || this.refDistance;
  60849. this.distanceModel = options.distanceModel || this.distanceModel;
  60850. this._playbackRate = options.playbackRate || this._playbackRate;
  60851. this._updateSpatialParameters();
  60852. if (this.isPlaying) {
  60853. if (this._streaming) {
  60854. this._htmlAudioElement.playbackRate = this._playbackRate;
  60855. }
  60856. else {
  60857. if (this._soundSource) {
  60858. this._soundSource.playbackRate.value = this._playbackRate;
  60859. }
  60860. }
  60861. }
  60862. }
  60863. };
  60864. Sound.prototype._createSpatialParameters = function () {
  60865. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60866. if (this._scene.headphone) {
  60867. this._panningModel = "HRTF";
  60868. }
  60869. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  60870. this._updateSpatialParameters();
  60871. this._soundPanner.connect(this._ouputAudioNode);
  60872. this._inputAudioNode = this._soundPanner;
  60873. }
  60874. };
  60875. Sound.prototype._updateSpatialParameters = function () {
  60876. if (this.spatialSound && this._soundPanner) {
  60877. if (this.useCustomAttenuation) {
  60878. // Tricks to disable in a way embedded Web Audio attenuation
  60879. this._soundPanner.distanceModel = "linear";
  60880. this._soundPanner.maxDistance = Number.MAX_VALUE;
  60881. this._soundPanner.refDistance = 1;
  60882. this._soundPanner.rolloffFactor = 1;
  60883. this._soundPanner.panningModel = this._panningModel;
  60884. }
  60885. else {
  60886. this._soundPanner.distanceModel = this.distanceModel;
  60887. this._soundPanner.maxDistance = this.maxDistance;
  60888. this._soundPanner.refDistance = this.refDistance;
  60889. this._soundPanner.rolloffFactor = this.rolloffFactor;
  60890. this._soundPanner.panningModel = this._panningModel;
  60891. }
  60892. }
  60893. };
  60894. Sound.prototype.switchPanningModelToHRTF = function () {
  60895. this._panningModel = "HRTF";
  60896. this._switchPanningModel();
  60897. };
  60898. Sound.prototype.switchPanningModelToEqualPower = function () {
  60899. this._panningModel = "equalpower";
  60900. this._switchPanningModel();
  60901. };
  60902. Sound.prototype._switchPanningModel = function () {
  60903. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  60904. this._soundPanner.panningModel = this._panningModel;
  60905. }
  60906. };
  60907. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  60908. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60909. if (this._isOutputConnected) {
  60910. this._ouputAudioNode.disconnect();
  60911. }
  60912. this._ouputAudioNode.connect(soundTrackAudioNode);
  60913. this._isOutputConnected = true;
  60914. }
  60915. };
  60916. /**
  60917. * Transform this sound into a directional source
  60918. * @param coneInnerAngle Size of the inner cone in degree
  60919. * @param coneOuterAngle Size of the outer cone in degree
  60920. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  60921. */
  60922. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  60923. if (coneOuterAngle < coneInnerAngle) {
  60924. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  60925. return;
  60926. }
  60927. this._coneInnerAngle = coneInnerAngle;
  60928. this._coneOuterAngle = coneOuterAngle;
  60929. this._coneOuterGain = coneOuterGain;
  60930. this._isDirectional = true;
  60931. if (this.isPlaying && this.loop) {
  60932. this.stop();
  60933. this.play();
  60934. }
  60935. };
  60936. Sound.prototype.setPosition = function (newPosition) {
  60937. this._position = newPosition;
  60938. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  60939. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  60940. }
  60941. };
  60942. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  60943. this._localDirection = newLocalDirection;
  60944. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  60945. this._updateDirection();
  60946. }
  60947. };
  60948. Sound.prototype._updateDirection = function () {
  60949. if (!this._connectedMesh || !this._soundPanner) {
  60950. return;
  60951. }
  60952. var mat = this._connectedMesh.getWorldMatrix();
  60953. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  60954. direction.normalize();
  60955. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  60956. };
  60957. Sound.prototype.updateDistanceFromListener = function () {
  60958. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  60959. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  60960. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  60961. }
  60962. };
  60963. Sound.prototype.setAttenuationFunction = function (callback) {
  60964. this._customAttenuationFunction = callback;
  60965. };
  60966. /**
  60967. * Play the sound
  60968. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  60969. * @param offset (optional) Start the sound setting it at a specific time
  60970. */
  60971. Sound.prototype.play = function (time, offset) {
  60972. var _this = this;
  60973. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  60974. try {
  60975. if (this._startOffset < 0) {
  60976. time = -this._startOffset;
  60977. this._startOffset = 0;
  60978. }
  60979. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  60980. if (!this._soundSource || !this._streamingSource) {
  60981. if (this.spatialSound && this._soundPanner) {
  60982. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  60983. if (this._isDirectional) {
  60984. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  60985. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  60986. this._soundPanner.coneOuterGain = this._coneOuterGain;
  60987. if (this._connectedMesh) {
  60988. this._updateDirection();
  60989. }
  60990. else {
  60991. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  60992. }
  60993. }
  60994. }
  60995. }
  60996. if (this._streaming) {
  60997. if (!this._streamingSource) {
  60998. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  60999. this._htmlAudioElement.onended = function () { _this._onended(); };
  61000. this._htmlAudioElement.playbackRate = this._playbackRate;
  61001. }
  61002. this._streamingSource.disconnect();
  61003. this._streamingSource.connect(this._inputAudioNode);
  61004. this._htmlAudioElement.play();
  61005. }
  61006. else {
  61007. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61008. this._soundSource.buffer = this._audioBuffer;
  61009. this._soundSource.connect(this._inputAudioNode);
  61010. this._soundSource.loop = this.loop;
  61011. this._soundSource.playbackRate.value = this._playbackRate;
  61012. this._soundSource.onended = function () { _this._onended(); };
  61013. if (this._soundSource.buffer) {
  61014. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61015. }
  61016. }
  61017. this._startTime = startTime;
  61018. this.isPlaying = true;
  61019. this.isPaused = false;
  61020. }
  61021. catch (ex) {
  61022. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  61023. }
  61024. }
  61025. };
  61026. Sound.prototype._onended = function () {
  61027. this.isPlaying = false;
  61028. if (this.onended) {
  61029. this.onended();
  61030. }
  61031. };
  61032. /**
  61033. * Stop the sound
  61034. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61035. */
  61036. Sound.prototype.stop = function (time) {
  61037. if (this.isPlaying) {
  61038. if (this._streaming) {
  61039. this._htmlAudioElement.pause();
  61040. // Test needed for Firefox or it will generate an Invalid State Error
  61041. if (this._htmlAudioElement.currentTime > 0) {
  61042. this._htmlAudioElement.currentTime = 0;
  61043. }
  61044. }
  61045. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61046. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61047. this._soundSource.stop(stopTime);
  61048. this._soundSource.onended = function () { };
  61049. if (!this.isPaused) {
  61050. this._startOffset = 0;
  61051. }
  61052. }
  61053. this.isPlaying = false;
  61054. }
  61055. };
  61056. Sound.prototype.pause = function () {
  61057. if (this.isPlaying) {
  61058. this.isPaused = true;
  61059. if (this._streaming) {
  61060. this._htmlAudioElement.pause();
  61061. }
  61062. else if (BABYLON.Engine.audioEngine.audioContext) {
  61063. this.stop(0);
  61064. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  61065. }
  61066. }
  61067. };
  61068. Sound.prototype.setVolume = function (newVolume, time) {
  61069. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  61070. if (time && BABYLON.Engine.audioEngine.audioContext) {
  61071. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  61072. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  61073. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  61074. }
  61075. else {
  61076. this._soundGain.gain.value = newVolume;
  61077. }
  61078. }
  61079. this._volume = newVolume;
  61080. };
  61081. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  61082. this._playbackRate = newPlaybackRate;
  61083. if (this.isPlaying) {
  61084. if (this._streaming) {
  61085. this._htmlAudioElement.playbackRate = this._playbackRate;
  61086. }
  61087. else if (this._soundSource) {
  61088. this._soundSource.playbackRate.value = this._playbackRate;
  61089. }
  61090. }
  61091. };
  61092. Sound.prototype.getVolume = function () {
  61093. return this._volume;
  61094. };
  61095. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  61096. var _this = this;
  61097. if (this._connectedMesh && this._registerFunc) {
  61098. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61099. this._registerFunc = null;
  61100. }
  61101. this._connectedMesh = meshToConnectTo;
  61102. if (!this.spatialSound) {
  61103. this.spatialSound = true;
  61104. this._createSpatialParameters();
  61105. if (this.isPlaying && this.loop) {
  61106. this.stop();
  61107. this.play();
  61108. }
  61109. }
  61110. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  61111. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  61112. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  61113. };
  61114. Sound.prototype.detachFromMesh = function () {
  61115. if (this._connectedMesh && this._registerFunc) {
  61116. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61117. this._registerFunc = null;
  61118. this._connectedMesh = null;
  61119. }
  61120. };
  61121. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  61122. if (!node.getBoundingInfo) {
  61123. return;
  61124. }
  61125. var mesh = node;
  61126. var boundingInfo = mesh.getBoundingInfo();
  61127. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  61128. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  61129. this._updateDirection();
  61130. }
  61131. };
  61132. Sound.prototype.clone = function () {
  61133. var _this = this;
  61134. if (!this._streaming) {
  61135. var setBufferAndRun = function () {
  61136. if (_this._isReadyToPlay) {
  61137. clonedSound._audioBuffer = _this.getAudioBuffer();
  61138. clonedSound._isReadyToPlay = true;
  61139. if (clonedSound.autoplay) {
  61140. clonedSound.play();
  61141. }
  61142. }
  61143. else {
  61144. window.setTimeout(setBufferAndRun, 300);
  61145. }
  61146. };
  61147. var currentOptions = {
  61148. autoplay: this.autoplay, loop: this.loop,
  61149. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  61150. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  61151. refDistance: this.refDistance, distanceModel: this.distanceModel
  61152. };
  61153. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  61154. if (this.useCustomAttenuation) {
  61155. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  61156. }
  61157. clonedSound.setPosition(this._position);
  61158. clonedSound.setPlaybackRate(this._playbackRate);
  61159. setBufferAndRun();
  61160. return clonedSound;
  61161. }
  61162. else {
  61163. return null;
  61164. }
  61165. };
  61166. Sound.prototype.getAudioBuffer = function () {
  61167. return this._audioBuffer;
  61168. };
  61169. Sound.prototype.serialize = function () {
  61170. var serializationObject = {
  61171. name: this.name,
  61172. url: this.name,
  61173. autoplay: this.autoplay,
  61174. loop: this.loop,
  61175. volume: this._volume,
  61176. spatialSound: this.spatialSound,
  61177. maxDistance: this.maxDistance,
  61178. rolloffFactor: this.rolloffFactor,
  61179. refDistance: this.refDistance,
  61180. distanceModel: this.distanceModel,
  61181. playbackRate: this._playbackRate,
  61182. panningModel: this._panningModel,
  61183. soundTrackId: this.soundTrackId
  61184. };
  61185. if (this.spatialSound) {
  61186. if (this._connectedMesh)
  61187. serializationObject.connectedMeshId = this._connectedMesh.id;
  61188. serializationObject.position = this._position.asArray();
  61189. serializationObject.refDistance = this.refDistance;
  61190. serializationObject.distanceModel = this.distanceModel;
  61191. serializationObject.isDirectional = this._isDirectional;
  61192. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  61193. serializationObject.coneInnerAngle = this._coneInnerAngle;
  61194. serializationObject.coneOuterAngle = this._coneOuterAngle;
  61195. serializationObject.coneOuterGain = this._coneOuterGain;
  61196. }
  61197. return serializationObject;
  61198. };
  61199. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  61200. var soundName = parsedSound.name;
  61201. var soundUrl;
  61202. if (parsedSound.url) {
  61203. soundUrl = rootUrl + parsedSound.url;
  61204. }
  61205. else {
  61206. soundUrl = rootUrl + soundName;
  61207. }
  61208. var options = {
  61209. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  61210. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  61211. rolloffFactor: parsedSound.rolloffFactor,
  61212. refDistance: parsedSound.refDistance,
  61213. distanceModel: parsedSound.distanceModel,
  61214. playbackRate: parsedSound.playbackRate
  61215. };
  61216. var newSound;
  61217. if (!sourceSound) {
  61218. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  61219. scene._addPendingData(newSound);
  61220. }
  61221. else {
  61222. var setBufferAndRun = function () {
  61223. if (sourceSound._isReadyToPlay) {
  61224. newSound._audioBuffer = sourceSound.getAudioBuffer();
  61225. newSound._isReadyToPlay = true;
  61226. if (newSound.autoplay) {
  61227. newSound.play();
  61228. }
  61229. }
  61230. else {
  61231. window.setTimeout(setBufferAndRun, 300);
  61232. }
  61233. };
  61234. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  61235. setBufferAndRun();
  61236. }
  61237. if (parsedSound.position) {
  61238. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  61239. newSound.setPosition(soundPosition);
  61240. }
  61241. if (parsedSound.isDirectional) {
  61242. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  61243. if (parsedSound.localDirectionToMesh) {
  61244. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  61245. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  61246. }
  61247. }
  61248. if (parsedSound.connectedMeshId) {
  61249. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  61250. if (connectedMesh) {
  61251. newSound.attachToMesh(connectedMesh);
  61252. }
  61253. }
  61254. return newSound;
  61255. };
  61256. return Sound;
  61257. }());
  61258. BABYLON.Sound = Sound;
  61259. })(BABYLON || (BABYLON = {}));
  61260. //# sourceMappingURL=babylon.sound.js.map
  61261. "use strict";
  61262. var BABYLON;
  61263. (function (BABYLON) {
  61264. var SoundTrack = /** @class */ (function () {
  61265. function SoundTrack(scene, options) {
  61266. this.id = -1;
  61267. this._isMainTrack = false;
  61268. this._isInitialized = false;
  61269. this._scene = scene;
  61270. this.soundCollection = new Array();
  61271. this._options = options;
  61272. if (!this._isMainTrack) {
  61273. this._scene.soundTracks.push(this);
  61274. this.id = this._scene.soundTracks.length - 1;
  61275. }
  61276. }
  61277. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  61278. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61279. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  61280. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  61281. if (this._options) {
  61282. if (this._options.volume) {
  61283. this._outputAudioNode.gain.value = this._options.volume;
  61284. }
  61285. if (this._options.mainTrack) {
  61286. this._isMainTrack = this._options.mainTrack;
  61287. }
  61288. }
  61289. this._isInitialized = true;
  61290. }
  61291. };
  61292. SoundTrack.prototype.dispose = function () {
  61293. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  61294. if (this._connectedAnalyser) {
  61295. this._connectedAnalyser.stopDebugCanvas();
  61296. }
  61297. while (this.soundCollection.length) {
  61298. this.soundCollection[0].dispose();
  61299. }
  61300. if (this._outputAudioNode) {
  61301. this._outputAudioNode.disconnect();
  61302. }
  61303. this._outputAudioNode = null;
  61304. }
  61305. };
  61306. SoundTrack.prototype.AddSound = function (sound) {
  61307. if (!this._isInitialized) {
  61308. this._initializeSoundTrackAudioGraph();
  61309. }
  61310. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61311. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  61312. }
  61313. if (sound.soundTrackId) {
  61314. if (sound.soundTrackId === -1) {
  61315. this._scene.mainSoundTrack.RemoveSound(sound);
  61316. }
  61317. else {
  61318. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  61319. }
  61320. }
  61321. this.soundCollection.push(sound);
  61322. sound.soundTrackId = this.id;
  61323. };
  61324. SoundTrack.prototype.RemoveSound = function (sound) {
  61325. var index = this.soundCollection.indexOf(sound);
  61326. if (index !== -1) {
  61327. this.soundCollection.splice(index, 1);
  61328. }
  61329. };
  61330. SoundTrack.prototype.setVolume = function (newVolume) {
  61331. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61332. this._outputAudioNode.gain.value = newVolume;
  61333. }
  61334. };
  61335. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  61336. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61337. for (var i = 0; i < this.soundCollection.length; i++) {
  61338. this.soundCollection[i].switchPanningModelToHRTF();
  61339. }
  61340. }
  61341. };
  61342. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  61343. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61344. for (var i = 0; i < this.soundCollection.length; i++) {
  61345. this.soundCollection[i].switchPanningModelToEqualPower();
  61346. }
  61347. }
  61348. };
  61349. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  61350. if (this._connectedAnalyser) {
  61351. this._connectedAnalyser.stopDebugCanvas();
  61352. }
  61353. this._connectedAnalyser = analyser;
  61354. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61355. this._outputAudioNode.disconnect();
  61356. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  61357. }
  61358. };
  61359. return SoundTrack;
  61360. }());
  61361. BABYLON.SoundTrack = SoundTrack;
  61362. })(BABYLON || (BABYLON = {}));
  61363. //# sourceMappingURL=babylon.soundtrack.js.map
  61364. "use strict";
  61365. var BABYLON;
  61366. (function (BABYLON) {
  61367. var Analyser = /** @class */ (function () {
  61368. function Analyser(scene) {
  61369. this.SMOOTHING = 0.75;
  61370. this.FFT_SIZE = 512;
  61371. this.BARGRAPHAMPLITUDE = 256;
  61372. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  61373. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  61374. this._scene = scene;
  61375. this._audioEngine = BABYLON.Engine.audioEngine;
  61376. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  61377. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  61378. this._webAudioAnalyser.minDecibels = -140;
  61379. this._webAudioAnalyser.maxDecibels = 0;
  61380. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61381. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61382. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  61383. }
  61384. }
  61385. Analyser.prototype.getFrequencyBinCount = function () {
  61386. if (this._audioEngine.canUseWebAudio) {
  61387. return this._webAudioAnalyser.frequencyBinCount;
  61388. }
  61389. else {
  61390. return 0;
  61391. }
  61392. };
  61393. Analyser.prototype.getByteFrequencyData = function () {
  61394. if (this._audioEngine.canUseWebAudio) {
  61395. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61396. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61397. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  61398. }
  61399. return this._byteFreqs;
  61400. };
  61401. Analyser.prototype.getByteTimeDomainData = function () {
  61402. if (this._audioEngine.canUseWebAudio) {
  61403. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61404. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61405. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  61406. }
  61407. return this._byteTime;
  61408. };
  61409. Analyser.prototype.getFloatFrequencyData = function () {
  61410. if (this._audioEngine.canUseWebAudio) {
  61411. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61412. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61413. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  61414. }
  61415. return this._floatFreqs;
  61416. };
  61417. Analyser.prototype.drawDebugCanvas = function () {
  61418. var _this = this;
  61419. if (this._audioEngine.canUseWebAudio) {
  61420. if (!this._debugCanvas) {
  61421. this._debugCanvas = document.createElement("canvas");
  61422. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  61423. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  61424. this._debugCanvas.style.position = "absolute";
  61425. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  61426. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  61427. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  61428. document.body.appendChild(this._debugCanvas);
  61429. this._registerFunc = function () {
  61430. _this.drawDebugCanvas();
  61431. };
  61432. this._scene.registerBeforeRender(this._registerFunc);
  61433. }
  61434. if (this._registerFunc && this._debugCanvasContext) {
  61435. var workingArray = this.getByteFrequencyData();
  61436. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  61437. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  61438. // Draw the frequency domain chart.
  61439. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  61440. var value = workingArray[i];
  61441. var percent = value / this.BARGRAPHAMPLITUDE;
  61442. var height = this.DEBUGCANVASSIZE.height * percent;
  61443. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  61444. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  61445. var hue = i / this.getFrequencyBinCount() * 360;
  61446. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  61447. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  61448. }
  61449. }
  61450. }
  61451. };
  61452. Analyser.prototype.stopDebugCanvas = function () {
  61453. if (this._debugCanvas) {
  61454. if (this._registerFunc) {
  61455. this._scene.unregisterBeforeRender(this._registerFunc);
  61456. this._registerFunc = null;
  61457. }
  61458. document.body.removeChild(this._debugCanvas);
  61459. this._debugCanvas = null;
  61460. this._debugCanvasContext = null;
  61461. }
  61462. };
  61463. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  61464. if (this._audioEngine.canUseWebAudio) {
  61465. inputAudioNode.connect(this._webAudioAnalyser);
  61466. this._webAudioAnalyser.connect(outputAudioNode);
  61467. }
  61468. };
  61469. Analyser.prototype.dispose = function () {
  61470. if (this._audioEngine.canUseWebAudio) {
  61471. this._webAudioAnalyser.disconnect();
  61472. }
  61473. };
  61474. return Analyser;
  61475. }());
  61476. BABYLON.Analyser = Analyser;
  61477. })(BABYLON || (BABYLON = {}));
  61478. //# sourceMappingURL=babylon.analyser.js.map
  61479. "use strict";
  61480. var BABYLON;
  61481. (function (BABYLON) {
  61482. var CubeTexture = /** @class */ (function (_super) {
  61483. __extends(CubeTexture, _super);
  61484. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  61485. if (extensions === void 0) { extensions = null; }
  61486. if (noMipmap === void 0) { noMipmap = false; }
  61487. if (files === void 0) { files = null; }
  61488. if (onLoad === void 0) { onLoad = null; }
  61489. if (onError === void 0) { onError = null; }
  61490. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  61491. if (prefiltered === void 0) { prefiltered = false; }
  61492. if (forcedExtension === void 0) { forcedExtension = null; }
  61493. var _this = _super.call(this, scene) || this;
  61494. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  61495. /**
  61496. * Gets or sets the center of the bounding box associated with the cube texture
  61497. * It must define where the camera used to render the texture was set
  61498. */
  61499. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61500. _this._rotationY = 0;
  61501. _this.name = rootUrl;
  61502. _this.url = rootUrl;
  61503. _this._noMipmap = noMipmap;
  61504. _this.hasAlpha = false;
  61505. _this._format = format;
  61506. _this._prefiltered = prefiltered;
  61507. _this.isCube = true;
  61508. _this._textureMatrix = BABYLON.Matrix.Identity();
  61509. if (prefiltered) {
  61510. _this.gammaSpace = false;
  61511. }
  61512. if (!rootUrl && !files) {
  61513. return _this;
  61514. }
  61515. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  61516. var lastDot = rootUrl.lastIndexOf(".");
  61517. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  61518. var isDDS = (extension === ".dds");
  61519. if (!files) {
  61520. if (!isDDS && !extensions) {
  61521. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  61522. }
  61523. files = [];
  61524. if (extensions) {
  61525. for (var index = 0; index < extensions.length; index++) {
  61526. files.push(rootUrl + extensions[index]);
  61527. }
  61528. }
  61529. }
  61530. _this._files = files;
  61531. if (!_this._texture) {
  61532. if (!scene.useDelayedTextureLoading) {
  61533. if (prefiltered) {
  61534. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  61535. }
  61536. else {
  61537. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  61538. }
  61539. }
  61540. else {
  61541. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61542. }
  61543. }
  61544. else if (onLoad) {
  61545. if (_this._texture.isReady) {
  61546. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  61547. }
  61548. else {
  61549. _this._texture.onLoadedObservable.add(onLoad);
  61550. }
  61551. }
  61552. return _this;
  61553. }
  61554. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  61555. get: function () {
  61556. return this._boundingBoxSize;
  61557. },
  61558. /**
  61559. * Gets or sets the size of the bounding box associated with the cube texture
  61560. * When defined, the cubemap will switch to local mode
  61561. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  61562. * @example https://www.babylonjs-playground.com/#RNASML
  61563. */
  61564. set: function (value) {
  61565. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  61566. return;
  61567. }
  61568. this._boundingBoxSize = value;
  61569. var scene = this.getScene();
  61570. if (scene) {
  61571. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  61572. }
  61573. },
  61574. enumerable: true,
  61575. configurable: true
  61576. });
  61577. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  61578. /**
  61579. * Gets texture matrix rotation angle around Y axis radians.
  61580. */
  61581. get: function () {
  61582. return this._rotationY;
  61583. },
  61584. /**
  61585. * Sets texture matrix rotation angle around Y axis in radians.
  61586. */
  61587. set: function (value) {
  61588. this._rotationY = value;
  61589. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  61590. },
  61591. enumerable: true,
  61592. configurable: true
  61593. });
  61594. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  61595. var rootUrlKey = "";
  61596. files.forEach(function (url) { return rootUrlKey += url; });
  61597. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  61598. };
  61599. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  61600. if (forcedExtension === void 0) { forcedExtension = null; }
  61601. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  61602. };
  61603. // Methods
  61604. CubeTexture.prototype.delayLoad = function () {
  61605. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  61606. return;
  61607. }
  61608. var scene = this.getScene();
  61609. if (!scene) {
  61610. return;
  61611. }
  61612. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61613. this._texture = this._getFromCache(this.url, this._noMipmap);
  61614. if (!this._texture) {
  61615. if (this._prefiltered) {
  61616. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  61617. }
  61618. else {
  61619. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  61620. }
  61621. }
  61622. };
  61623. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  61624. return this._textureMatrix;
  61625. };
  61626. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  61627. this._textureMatrix = value;
  61628. };
  61629. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61630. var texture = BABYLON.SerializationHelper.Parse(function () {
  61631. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  61632. }, parsedTexture, scene);
  61633. // Local Cubemaps
  61634. if (parsedTexture.boundingBoxPosition) {
  61635. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  61636. }
  61637. if (parsedTexture.boundingBoxSize) {
  61638. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  61639. }
  61640. // Animations
  61641. if (parsedTexture.animations) {
  61642. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  61643. var parsedAnimation = parsedTexture.animations[animationIndex];
  61644. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  61645. }
  61646. }
  61647. return texture;
  61648. };
  61649. CubeTexture.prototype.clone = function () {
  61650. var _this = this;
  61651. return BABYLON.SerializationHelper.Clone(function () {
  61652. var scene = _this.getScene();
  61653. if (!scene) {
  61654. return _this;
  61655. }
  61656. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  61657. }, this);
  61658. };
  61659. __decorate([
  61660. BABYLON.serialize("rotationY")
  61661. ], CubeTexture.prototype, "_rotationY", void 0);
  61662. return CubeTexture;
  61663. }(BABYLON.BaseTexture));
  61664. BABYLON.CubeTexture = CubeTexture;
  61665. })(BABYLON || (BABYLON = {}));
  61666. //# sourceMappingURL=babylon.cubeTexture.js.map
  61667. "use strict";
  61668. var BABYLON;
  61669. (function (BABYLON) {
  61670. var RenderTargetTexture = /** @class */ (function (_super) {
  61671. __extends(RenderTargetTexture, _super);
  61672. /**
  61673. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  61674. * or used a shadow, depth texture...
  61675. * @param name The friendly name of the texture
  61676. * @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)
  61677. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  61678. * @param generateMipMaps True if mip maps need to be generated after render.
  61679. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  61680. * @param type The type of the buffer in the RTT (int, half float, float...)
  61681. * @param isCube True if a cube texture needs to be created
  61682. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  61683. * @param generateDepthBuffer True to generate a depth buffer
  61684. * @param generateStencilBuffer True to generate a stencil buffer
  61685. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  61686. */
  61687. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  61688. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  61689. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61690. if (isCube === void 0) { isCube = false; }
  61691. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61692. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  61693. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  61694. if (isMulti === void 0) { isMulti = false; }
  61695. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61696. _this.isCube = isCube;
  61697. /**
  61698. * Use this list to define the list of mesh you want to render.
  61699. */
  61700. _this.renderList = new Array();
  61701. _this.renderParticles = true;
  61702. _this.renderSprites = false;
  61703. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  61704. _this.ignoreCameraViewport = false;
  61705. // Events
  61706. /**
  61707. * An event triggered when the texture is unbind.
  61708. */
  61709. _this.onBeforeBindObservable = new BABYLON.Observable();
  61710. /**
  61711. * An event triggered when the texture is unbind.
  61712. */
  61713. _this.onAfterUnbindObservable = new BABYLON.Observable();
  61714. /**
  61715. * An event triggered before rendering the texture
  61716. */
  61717. _this.onBeforeRenderObservable = new BABYLON.Observable();
  61718. /**
  61719. * An event triggered after rendering the texture
  61720. */
  61721. _this.onAfterRenderObservable = new BABYLON.Observable();
  61722. /**
  61723. * An event triggered after the texture clear
  61724. */
  61725. _this.onClearObservable = new BABYLON.Observable();
  61726. _this._currentRefreshId = -1;
  61727. _this._refreshRate = 1;
  61728. _this._samples = 1;
  61729. /**
  61730. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  61731. * It must define where the camera used to render the texture is set
  61732. */
  61733. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61734. scene = _this.getScene();
  61735. if (!scene) {
  61736. return _this;
  61737. }
  61738. _this._engine = scene.getEngine();
  61739. _this.name = name;
  61740. _this.isRenderTarget = true;
  61741. _this._initialSizeParameter = size;
  61742. _this._processSizeParameter(size);
  61743. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  61744. });
  61745. _this._generateMipMaps = generateMipMaps ? true : false;
  61746. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  61747. // Rendering groups
  61748. _this._renderingManager = new BABYLON.RenderingManager(scene);
  61749. if (isMulti) {
  61750. return _this;
  61751. }
  61752. _this._renderTargetOptions = {
  61753. generateMipMaps: generateMipMaps,
  61754. type: type,
  61755. samplingMode: samplingMode,
  61756. generateDepthBuffer: generateDepthBuffer,
  61757. generateStencilBuffer: generateStencilBuffer
  61758. };
  61759. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  61760. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61761. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61762. }
  61763. if (isCube) {
  61764. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  61765. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  61766. _this._textureMatrix = BABYLON.Matrix.Identity();
  61767. }
  61768. else {
  61769. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  61770. }
  61771. return _this;
  61772. }
  61773. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  61774. get: function () {
  61775. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  61776. },
  61777. enumerable: true,
  61778. configurable: true
  61779. });
  61780. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  61781. get: function () {
  61782. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  61783. },
  61784. enumerable: true,
  61785. configurable: true
  61786. });
  61787. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  61788. get: function () {
  61789. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  61790. },
  61791. enumerable: true,
  61792. configurable: true
  61793. });
  61794. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  61795. set: function (callback) {
  61796. if (this._onAfterUnbindObserver) {
  61797. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  61798. }
  61799. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  61800. },
  61801. enumerable: true,
  61802. configurable: true
  61803. });
  61804. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  61805. set: function (callback) {
  61806. if (this._onBeforeRenderObserver) {
  61807. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  61808. }
  61809. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  61810. },
  61811. enumerable: true,
  61812. configurable: true
  61813. });
  61814. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  61815. set: function (callback) {
  61816. if (this._onAfterRenderObserver) {
  61817. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  61818. }
  61819. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  61820. },
  61821. enumerable: true,
  61822. configurable: true
  61823. });
  61824. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  61825. set: function (callback) {
  61826. if (this._onClearObserver) {
  61827. this.onClearObservable.remove(this._onClearObserver);
  61828. }
  61829. this._onClearObserver = this.onClearObservable.add(callback);
  61830. },
  61831. enumerable: true,
  61832. configurable: true
  61833. });
  61834. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  61835. get: function () {
  61836. return this._renderTargetOptions;
  61837. },
  61838. enumerable: true,
  61839. configurable: true
  61840. });
  61841. RenderTargetTexture.prototype._onRatioRescale = function () {
  61842. if (this._sizeRatio) {
  61843. this.resize(this._initialSizeParameter);
  61844. }
  61845. };
  61846. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  61847. get: function () {
  61848. return this._boundingBoxSize;
  61849. },
  61850. /**
  61851. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  61852. * When defined, the cubemap will switch to local mode
  61853. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  61854. * @example https://www.babylonjs-playground.com/#RNASML
  61855. */
  61856. set: function (value) {
  61857. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  61858. return;
  61859. }
  61860. this._boundingBoxSize = value;
  61861. var scene = this.getScene();
  61862. if (scene) {
  61863. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  61864. }
  61865. },
  61866. enumerable: true,
  61867. configurable: true
  61868. });
  61869. /**
  61870. * Creates a depth stencil texture.
  61871. * This is only available in WebGL 2 or with the depth texture extension available.
  61872. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  61873. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  61874. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  61875. */
  61876. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  61877. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  61878. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  61879. if (generateStencil === void 0) { generateStencil = false; }
  61880. if (!this.getScene()) {
  61881. return;
  61882. }
  61883. var engine = this.getScene().getEngine();
  61884. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  61885. bilinearFiltering: bilinearFiltering,
  61886. comparisonFunction: comparisonFunction,
  61887. generateStencil: generateStencil,
  61888. isCube: this.isCube
  61889. });
  61890. engine.setFrameBufferDepthStencilTexture(this);
  61891. };
  61892. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  61893. if (size.ratio) {
  61894. this._sizeRatio = size.ratio;
  61895. this._size = {
  61896. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  61897. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  61898. };
  61899. }
  61900. else {
  61901. this._size = size;
  61902. }
  61903. };
  61904. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  61905. get: function () {
  61906. return this._samples;
  61907. },
  61908. set: function (value) {
  61909. if (this._samples === value) {
  61910. return;
  61911. }
  61912. var scene = this.getScene();
  61913. if (!scene) {
  61914. return;
  61915. }
  61916. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  61917. },
  61918. enumerable: true,
  61919. configurable: true
  61920. });
  61921. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  61922. this._currentRefreshId = -1;
  61923. };
  61924. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  61925. get: function () {
  61926. return this._refreshRate;
  61927. },
  61928. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  61929. set: function (value) {
  61930. this._refreshRate = value;
  61931. this.resetRefreshCounter();
  61932. },
  61933. enumerable: true,
  61934. configurable: true
  61935. });
  61936. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  61937. if (!this._postProcessManager) {
  61938. var scene = this.getScene();
  61939. if (!scene) {
  61940. return;
  61941. }
  61942. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  61943. this._postProcesses = new Array();
  61944. }
  61945. this._postProcesses.push(postProcess);
  61946. this._postProcesses[0].autoClear = false;
  61947. };
  61948. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  61949. if (!this._postProcesses) {
  61950. return;
  61951. }
  61952. if (dispose) {
  61953. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  61954. var postProcess = _a[_i];
  61955. postProcess.dispose();
  61956. }
  61957. }
  61958. this._postProcesses = [];
  61959. };
  61960. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  61961. if (!this._postProcesses) {
  61962. return;
  61963. }
  61964. var index = this._postProcesses.indexOf(postProcess);
  61965. if (index === -1) {
  61966. return;
  61967. }
  61968. this._postProcesses.splice(index, 1);
  61969. if (this._postProcesses.length > 0) {
  61970. this._postProcesses[0].autoClear = false;
  61971. }
  61972. };
  61973. RenderTargetTexture.prototype._shouldRender = function () {
  61974. if (this._currentRefreshId === -1) {
  61975. this._currentRefreshId = 1;
  61976. return true;
  61977. }
  61978. if (this.refreshRate === this._currentRefreshId) {
  61979. this._currentRefreshId = 1;
  61980. return true;
  61981. }
  61982. this._currentRefreshId++;
  61983. return false;
  61984. };
  61985. RenderTargetTexture.prototype.getRenderSize = function () {
  61986. if (this._size.width) {
  61987. return this._size.width;
  61988. }
  61989. return this._size;
  61990. };
  61991. RenderTargetTexture.prototype.getRenderWidth = function () {
  61992. if (this._size.width) {
  61993. return this._size.width;
  61994. }
  61995. return this._size;
  61996. };
  61997. RenderTargetTexture.prototype.getRenderHeight = function () {
  61998. if (this._size.width) {
  61999. return this._size.height;
  62000. }
  62001. return this._size;
  62002. };
  62003. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62004. get: function () {
  62005. return true;
  62006. },
  62007. enumerable: true,
  62008. configurable: true
  62009. });
  62010. RenderTargetTexture.prototype.scale = function (ratio) {
  62011. var newSize = this.getRenderSize() * ratio;
  62012. this.resize(newSize);
  62013. };
  62014. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62015. if (this.isCube) {
  62016. return this._textureMatrix;
  62017. }
  62018. return _super.prototype.getReflectionTextureMatrix.call(this);
  62019. };
  62020. RenderTargetTexture.prototype.resize = function (size) {
  62021. this.releaseInternalTexture();
  62022. var scene = this.getScene();
  62023. if (!scene) {
  62024. return;
  62025. }
  62026. this._processSizeParameter(size);
  62027. if (this.isCube) {
  62028. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62029. }
  62030. else {
  62031. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62032. }
  62033. };
  62034. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62035. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62036. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62037. var scene = this.getScene();
  62038. if (!scene) {
  62039. return;
  62040. }
  62041. var engine = scene.getEngine();
  62042. if (this.useCameraPostProcesses !== undefined) {
  62043. useCameraPostProcess = this.useCameraPostProcesses;
  62044. }
  62045. if (this._waitingRenderList) {
  62046. this.renderList = [];
  62047. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62048. var id = this._waitingRenderList[index];
  62049. var mesh_1 = scene.getMeshByID(id);
  62050. if (mesh_1) {
  62051. this.renderList.push(mesh_1);
  62052. }
  62053. }
  62054. delete this._waitingRenderList;
  62055. }
  62056. // Is predicate defined?
  62057. if (this.renderListPredicate) {
  62058. if (this.renderList) {
  62059. this.renderList.splice(0); // Clear previous renderList
  62060. }
  62061. else {
  62062. this.renderList = [];
  62063. }
  62064. var scene = this.getScene();
  62065. if (!scene) {
  62066. return;
  62067. }
  62068. var sceneMeshes = scene.meshes;
  62069. for (var index = 0; index < sceneMeshes.length; index++) {
  62070. var mesh = sceneMeshes[index];
  62071. if (this.renderListPredicate(mesh)) {
  62072. this.renderList.push(mesh);
  62073. }
  62074. }
  62075. }
  62076. this.onBeforeBindObservable.notifyObservers(this);
  62077. // Set custom projection.
  62078. // Needs to be before binding to prevent changing the aspect ratio.
  62079. var camera;
  62080. if (this.activeCamera) {
  62081. camera = this.activeCamera;
  62082. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62083. if (this.activeCamera !== scene.activeCamera) {
  62084. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  62085. }
  62086. }
  62087. else {
  62088. camera = scene.activeCamera;
  62089. if (camera) {
  62090. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62091. }
  62092. }
  62093. // Prepare renderingManager
  62094. this._renderingManager.reset();
  62095. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  62096. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  62097. var sceneRenderId = scene.getRenderId();
  62098. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  62099. var mesh = currentRenderList[meshIndex];
  62100. if (mesh) {
  62101. if (!mesh.isReady(this.refreshRate === 0)) {
  62102. this.resetRefreshCounter();
  62103. continue;
  62104. }
  62105. mesh._preActivateForIntermediateRendering(sceneRenderId);
  62106. var isMasked = void 0;
  62107. if (!this.renderList && camera) {
  62108. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  62109. }
  62110. else {
  62111. isMasked = false;
  62112. }
  62113. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  62114. mesh._activate(sceneRenderId);
  62115. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  62116. var subMesh = mesh.subMeshes[subIndex];
  62117. scene._activeIndices.addCount(subMesh.indexCount, false);
  62118. this._renderingManager.dispatch(subMesh, mesh);
  62119. }
  62120. }
  62121. }
  62122. }
  62123. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  62124. var particleSystem = scene.particleSystems[particleIndex];
  62125. var emitter = particleSystem.emitter;
  62126. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  62127. continue;
  62128. }
  62129. if (currentRenderList.indexOf(emitter) >= 0) {
  62130. this._renderingManager.dispatchParticles(particleSystem);
  62131. }
  62132. }
  62133. if (this.isCube) {
  62134. for (var face = 0; face < 6; face++) {
  62135. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62136. scene.incrementRenderId();
  62137. scene.resetCachedMaterial();
  62138. }
  62139. }
  62140. else {
  62141. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62142. }
  62143. this.onAfterUnbindObservable.notifyObservers(this);
  62144. if (scene.activeCamera) {
  62145. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  62146. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  62147. }
  62148. engine.setViewport(scene.activeCamera.viewport);
  62149. }
  62150. scene.resetCachedMaterial();
  62151. };
  62152. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  62153. var minimum = 128;
  62154. var x = renderDimension * scale;
  62155. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  62156. // Ensure we don't exceed the render dimension (while staying POT)
  62157. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  62158. };
  62159. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62160. var _this = this;
  62161. if (!this._texture) {
  62162. return;
  62163. }
  62164. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  62165. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62166. });
  62167. };
  62168. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  62169. var scene = this.getScene();
  62170. if (!scene) {
  62171. return;
  62172. }
  62173. var engine = scene.getEngine();
  62174. if (!this._texture) {
  62175. return;
  62176. }
  62177. // Bind
  62178. if (this._postProcessManager) {
  62179. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  62180. }
  62181. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  62182. if (this._texture) {
  62183. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  62184. }
  62185. }
  62186. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  62187. // Clear
  62188. if (this.onClearObservable.hasObservers()) {
  62189. this.onClearObservable.notifyObservers(engine);
  62190. }
  62191. else {
  62192. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  62193. }
  62194. if (!this._doNotChangeAspectRatio) {
  62195. scene.updateTransformMatrix(true);
  62196. }
  62197. // Render
  62198. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  62199. if (this._postProcessManager) {
  62200. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  62201. }
  62202. else if (useCameraPostProcess) {
  62203. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  62204. }
  62205. if (!this._doNotChangeAspectRatio) {
  62206. scene.updateTransformMatrix(true);
  62207. }
  62208. // Dump ?
  62209. if (dumpForDebug) {
  62210. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  62211. }
  62212. // Unbind
  62213. if (!this.isCube || faceIndex === 5) {
  62214. if (this.isCube) {
  62215. if (faceIndex === 5) {
  62216. engine.generateMipMapsForCubemap(this._texture);
  62217. }
  62218. }
  62219. this.unbindFrameBuffer(engine, faceIndex);
  62220. }
  62221. else {
  62222. this.onAfterRenderObservable.notifyObservers(faceIndex);
  62223. }
  62224. };
  62225. /**
  62226. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  62227. * This allowed control for front to back rendering or reversly depending of the special needs.
  62228. *
  62229. * @param renderingGroupId The rendering group id corresponding to its index
  62230. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  62231. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  62232. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  62233. */
  62234. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  62235. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  62236. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  62237. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  62238. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  62239. };
  62240. /**
  62241. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  62242. *
  62243. * @param renderingGroupId The rendering group id corresponding to its index
  62244. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  62245. */
  62246. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  62247. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  62248. };
  62249. RenderTargetTexture.prototype.clone = function () {
  62250. var textureSize = this.getSize();
  62251. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  62252. // Base texture
  62253. newTexture.hasAlpha = this.hasAlpha;
  62254. newTexture.level = this.level;
  62255. // RenderTarget Texture
  62256. newTexture.coordinatesMode = this.coordinatesMode;
  62257. if (this.renderList) {
  62258. newTexture.renderList = this.renderList.slice(0);
  62259. }
  62260. return newTexture;
  62261. };
  62262. RenderTargetTexture.prototype.serialize = function () {
  62263. if (!this.name) {
  62264. return null;
  62265. }
  62266. var serializationObject = _super.prototype.serialize.call(this);
  62267. serializationObject.renderTargetSize = this.getRenderSize();
  62268. serializationObject.renderList = [];
  62269. if (this.renderList) {
  62270. for (var index = 0; index < this.renderList.length; index++) {
  62271. serializationObject.renderList.push(this.renderList[index].id);
  62272. }
  62273. }
  62274. return serializationObject;
  62275. };
  62276. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  62277. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  62278. var objBuffer = this.getInternalTexture();
  62279. var scene = this.getScene();
  62280. if (objBuffer && scene) {
  62281. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  62282. }
  62283. };
  62284. RenderTargetTexture.prototype.dispose = function () {
  62285. if (this._postProcessManager) {
  62286. this._postProcessManager.dispose();
  62287. this._postProcessManager = null;
  62288. }
  62289. this.clearPostProcesses(true);
  62290. if (this._resizeObserver) {
  62291. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  62292. this._resizeObserver = null;
  62293. }
  62294. this.renderList = null;
  62295. // Remove from custom render targets
  62296. var scene = this.getScene();
  62297. if (!scene) {
  62298. return;
  62299. }
  62300. var index = scene.customRenderTargets.indexOf(this);
  62301. if (index >= 0) {
  62302. scene.customRenderTargets.splice(index, 1);
  62303. }
  62304. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  62305. var camera = _a[_i];
  62306. index = camera.customRenderTargets.indexOf(this);
  62307. if (index >= 0) {
  62308. camera.customRenderTargets.splice(index, 1);
  62309. }
  62310. }
  62311. _super.prototype.dispose.call(this);
  62312. };
  62313. RenderTargetTexture.prototype._rebuild = function () {
  62314. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62315. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62316. }
  62317. if (this._postProcessManager) {
  62318. this._postProcessManager._rebuild();
  62319. }
  62320. };
  62321. /**
  62322. * Clear the info related to rendering groups preventing retention point in material dispose.
  62323. */
  62324. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  62325. if (this._renderingManager) {
  62326. this._renderingManager.freeRenderingGroups();
  62327. }
  62328. };
  62329. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  62330. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  62331. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  62332. return RenderTargetTexture;
  62333. }(BABYLON.Texture));
  62334. BABYLON.RenderTargetTexture = RenderTargetTexture;
  62335. })(BABYLON || (BABYLON = {}));
  62336. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  62337. "use strict";
  62338. var BABYLON;
  62339. (function (BABYLON) {
  62340. ;
  62341. var MultiRenderTarget = /** @class */ (function (_super) {
  62342. __extends(MultiRenderTarget, _super);
  62343. function MultiRenderTarget(name, size, count, scene, options) {
  62344. var _this = this;
  62345. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  62346. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  62347. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  62348. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  62349. _this._engine = scene.getEngine();
  62350. if (!_this.isSupported) {
  62351. _this.dispose();
  62352. return;
  62353. }
  62354. var types = [];
  62355. var samplingModes = [];
  62356. for (var i = 0; i < count; i++) {
  62357. if (options && options.types && options.types[i] !== undefined) {
  62358. types.push(options.types[i]);
  62359. }
  62360. else {
  62361. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62362. }
  62363. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  62364. samplingModes.push(options.samplingModes[i]);
  62365. }
  62366. else {
  62367. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62368. }
  62369. }
  62370. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  62371. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  62372. _this._size = size;
  62373. _this._multiRenderTargetOptions = {
  62374. samplingModes: samplingModes,
  62375. generateMipMaps: generateMipMaps,
  62376. generateDepthBuffer: generateDepthBuffer,
  62377. generateStencilBuffer: generateStencilBuffer,
  62378. generateDepthTexture: generateDepthTexture,
  62379. types: types,
  62380. textureCount: count
  62381. };
  62382. _this._createInternalTextures();
  62383. _this._createTextures();
  62384. return _this;
  62385. }
  62386. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  62387. get: function () {
  62388. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  62389. },
  62390. enumerable: true,
  62391. configurable: true
  62392. });
  62393. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  62394. get: function () {
  62395. return this._textures;
  62396. },
  62397. enumerable: true,
  62398. configurable: true
  62399. });
  62400. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  62401. get: function () {
  62402. return this._textures[this._textures.length - 1];
  62403. },
  62404. enumerable: true,
  62405. configurable: true
  62406. });
  62407. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  62408. set: function (wrap) {
  62409. if (this._textures) {
  62410. for (var i = 0; i < this._textures.length; i++) {
  62411. this._textures[i].wrapU = wrap;
  62412. }
  62413. }
  62414. },
  62415. enumerable: true,
  62416. configurable: true
  62417. });
  62418. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  62419. set: function (wrap) {
  62420. if (this._textures) {
  62421. for (var i = 0; i < this._textures.length; i++) {
  62422. this._textures[i].wrapV = wrap;
  62423. }
  62424. }
  62425. },
  62426. enumerable: true,
  62427. configurable: true
  62428. });
  62429. MultiRenderTarget.prototype._rebuild = function () {
  62430. this.releaseInternalTextures();
  62431. this._createInternalTextures();
  62432. for (var i = 0; i < this._internalTextures.length; i++) {
  62433. var texture = this._textures[i];
  62434. texture._texture = this._internalTextures[i];
  62435. }
  62436. // Keeps references to frame buffer and stencil/depth buffer
  62437. this._texture = this._internalTextures[0];
  62438. };
  62439. MultiRenderTarget.prototype._createInternalTextures = function () {
  62440. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  62441. };
  62442. MultiRenderTarget.prototype._createTextures = function () {
  62443. this._textures = [];
  62444. for (var i = 0; i < this._internalTextures.length; i++) {
  62445. var texture = new BABYLON.Texture(null, this.getScene());
  62446. texture._texture = this._internalTextures[i];
  62447. this._textures.push(texture);
  62448. }
  62449. // Keeps references to frame buffer and stencil/depth buffer
  62450. this._texture = this._internalTextures[0];
  62451. };
  62452. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  62453. get: function () {
  62454. return this._samples;
  62455. },
  62456. set: function (value) {
  62457. if (this._samples === value) {
  62458. return;
  62459. }
  62460. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  62461. },
  62462. enumerable: true,
  62463. configurable: true
  62464. });
  62465. MultiRenderTarget.prototype.resize = function (size) {
  62466. this.releaseInternalTextures();
  62467. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  62468. this._createInternalTextures();
  62469. };
  62470. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62471. var _this = this;
  62472. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  62473. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62474. });
  62475. };
  62476. MultiRenderTarget.prototype.dispose = function () {
  62477. this.releaseInternalTextures();
  62478. _super.prototype.dispose.call(this);
  62479. };
  62480. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  62481. if (!this._internalTextures) {
  62482. return;
  62483. }
  62484. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  62485. if (this._internalTextures[i] !== undefined) {
  62486. this._internalTextures[i].dispose();
  62487. this._internalTextures.splice(i, 1);
  62488. }
  62489. }
  62490. };
  62491. return MultiRenderTarget;
  62492. }(BABYLON.RenderTargetTexture));
  62493. BABYLON.MultiRenderTarget = MultiRenderTarget;
  62494. })(BABYLON || (BABYLON = {}));
  62495. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  62496. "use strict";
  62497. var BABYLON;
  62498. (function (BABYLON) {
  62499. var MirrorTexture = /** @class */ (function (_super) {
  62500. __extends(MirrorTexture, _super);
  62501. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  62502. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62504. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62505. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  62506. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  62507. _this._transformMatrix = BABYLON.Matrix.Zero();
  62508. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  62509. _this._adaptiveBlurKernel = 0;
  62510. _this._blurKernelX = 0;
  62511. _this._blurKernelY = 0;
  62512. _this._blurRatio = 1.0;
  62513. _this.ignoreCameraViewport = true;
  62514. _this.onBeforeRenderObservable.add(function () {
  62515. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  62516. _this._savedViewMatrix = scene.getViewMatrix();
  62517. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  62518. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  62519. scene.clipPlane = _this.mirrorPlane;
  62520. scene.getEngine().cullBackFaces = false;
  62521. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  62522. });
  62523. _this.onAfterRenderObservable.add(function () {
  62524. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  62525. scene.getEngine().cullBackFaces = true;
  62526. scene._mirroredCameraPosition = null;
  62527. delete scene.clipPlane;
  62528. });
  62529. return _this;
  62530. }
  62531. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  62532. get: function () {
  62533. return this._blurRatio;
  62534. },
  62535. set: function (value) {
  62536. if (this._blurRatio === value) {
  62537. return;
  62538. }
  62539. this._blurRatio = value;
  62540. this._preparePostProcesses();
  62541. },
  62542. enumerable: true,
  62543. configurable: true
  62544. });
  62545. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  62546. set: function (value) {
  62547. this._adaptiveBlurKernel = value;
  62548. this._autoComputeBlurKernel();
  62549. },
  62550. enumerable: true,
  62551. configurable: true
  62552. });
  62553. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  62554. set: function (value) {
  62555. this.blurKernelX = value;
  62556. this.blurKernelY = value;
  62557. },
  62558. enumerable: true,
  62559. configurable: true
  62560. });
  62561. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  62562. get: function () {
  62563. return this._blurKernelX;
  62564. },
  62565. set: function (value) {
  62566. if (this._blurKernelX === value) {
  62567. return;
  62568. }
  62569. this._blurKernelX = value;
  62570. this._preparePostProcesses();
  62571. },
  62572. enumerable: true,
  62573. configurable: true
  62574. });
  62575. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  62576. get: function () {
  62577. return this._blurKernelY;
  62578. },
  62579. set: function (value) {
  62580. if (this._blurKernelY === value) {
  62581. return;
  62582. }
  62583. this._blurKernelY = value;
  62584. this._preparePostProcesses();
  62585. },
  62586. enumerable: true,
  62587. configurable: true
  62588. });
  62589. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  62590. var engine = this.getScene().getEngine();
  62591. var dw = this.getRenderWidth() / engine.getRenderWidth();
  62592. var dh = this.getRenderHeight() / engine.getRenderHeight();
  62593. this.blurKernelX = this._adaptiveBlurKernel * dw;
  62594. this.blurKernelY = this._adaptiveBlurKernel * dh;
  62595. };
  62596. MirrorTexture.prototype._onRatioRescale = function () {
  62597. if (this._sizeRatio) {
  62598. this.resize(this._initialSizeParameter);
  62599. if (!this._adaptiveBlurKernel) {
  62600. this._preparePostProcesses();
  62601. }
  62602. }
  62603. if (this._adaptiveBlurKernel) {
  62604. this._autoComputeBlurKernel();
  62605. }
  62606. };
  62607. MirrorTexture.prototype._preparePostProcesses = function () {
  62608. this.clearPostProcesses(true);
  62609. if (this._blurKernelX && this._blurKernelY) {
  62610. var engine = this.getScene().getEngine();
  62611. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62612. 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);
  62613. this._blurX.autoClear = false;
  62614. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  62615. this._blurX.inputTexture = this._texture;
  62616. }
  62617. else {
  62618. this._blurX.alwaysForcePOT = true;
  62619. }
  62620. 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);
  62621. this._blurY.autoClear = false;
  62622. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  62623. this.addPostProcess(this._blurX);
  62624. this.addPostProcess(this._blurY);
  62625. }
  62626. else {
  62627. if (this._blurY) {
  62628. this.removePostProcess(this._blurY);
  62629. this._blurY.dispose();
  62630. this._blurY = null;
  62631. }
  62632. if (this._blurX) {
  62633. this.removePostProcess(this._blurX);
  62634. this._blurX.dispose();
  62635. this._blurX = null;
  62636. }
  62637. }
  62638. };
  62639. MirrorTexture.prototype.clone = function () {
  62640. var scene = this.getScene();
  62641. if (!scene) {
  62642. return this;
  62643. }
  62644. var textureSize = this.getSize();
  62645. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  62646. // Base texture
  62647. newTexture.hasAlpha = this.hasAlpha;
  62648. newTexture.level = this.level;
  62649. // Mirror Texture
  62650. newTexture.mirrorPlane = this.mirrorPlane.clone();
  62651. if (this.renderList) {
  62652. newTexture.renderList = this.renderList.slice(0);
  62653. }
  62654. return newTexture;
  62655. };
  62656. MirrorTexture.prototype.serialize = function () {
  62657. if (!this.name) {
  62658. return null;
  62659. }
  62660. var serializationObject = _super.prototype.serialize.call(this);
  62661. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  62662. return serializationObject;
  62663. };
  62664. return MirrorTexture;
  62665. }(BABYLON.RenderTargetTexture));
  62666. BABYLON.MirrorTexture = MirrorTexture;
  62667. })(BABYLON || (BABYLON = {}));
  62668. //# sourceMappingURL=babylon.mirrorTexture.js.map
  62669. "use strict";
  62670. var BABYLON;
  62671. (function (BABYLON) {
  62672. /**
  62673. * Creates a refraction texture used by refraction channel of the standard material.
  62674. * @param name the texture name
  62675. * @param size size of the underlying texture
  62676. * @param scene root scene
  62677. */
  62678. var RefractionTexture = /** @class */ (function (_super) {
  62679. __extends(RefractionTexture, _super);
  62680. function RefractionTexture(name, size, scene, generateMipMaps) {
  62681. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  62682. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  62683. _this.depth = 2.0;
  62684. _this.onBeforeRenderObservable.add(function () {
  62685. scene.clipPlane = _this.refractionPlane;
  62686. });
  62687. _this.onAfterRenderObservable.add(function () {
  62688. delete scene.clipPlane;
  62689. });
  62690. return _this;
  62691. }
  62692. RefractionTexture.prototype.clone = function () {
  62693. var scene = this.getScene();
  62694. if (!scene) {
  62695. return this;
  62696. }
  62697. var textureSize = this.getSize();
  62698. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  62699. // Base texture
  62700. newTexture.hasAlpha = this.hasAlpha;
  62701. newTexture.level = this.level;
  62702. // Refraction Texture
  62703. newTexture.refractionPlane = this.refractionPlane.clone();
  62704. if (this.renderList) {
  62705. newTexture.renderList = this.renderList.slice(0);
  62706. }
  62707. newTexture.depth = this.depth;
  62708. return newTexture;
  62709. };
  62710. RefractionTexture.prototype.serialize = function () {
  62711. if (!this.name) {
  62712. return null;
  62713. }
  62714. var serializationObject = _super.prototype.serialize.call(this);
  62715. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  62716. serializationObject.depth = this.depth;
  62717. return serializationObject;
  62718. };
  62719. return RefractionTexture;
  62720. }(BABYLON.RenderTargetTexture));
  62721. BABYLON.RefractionTexture = RefractionTexture;
  62722. })(BABYLON || (BABYLON = {}));
  62723. //# sourceMappingURL=babylon.refractionTexture.js.map
  62724. "use strict";
  62725. var BABYLON;
  62726. (function (BABYLON) {
  62727. /**
  62728. * A class extending {BABYLON.Texture} allowing drawing on a texture
  62729. * @see http://doc.babylonjs.com/how_to/dynamictexture
  62730. */
  62731. var DynamicTexture = /** @class */ (function (_super) {
  62732. __extends(DynamicTexture, _super);
  62733. /**
  62734. * Creates a {BABYLON.DynamicTexture}
  62735. * @param name defines the name of the texture
  62736. * @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
  62737. * @param scene defines the scene where you want the texture
  62738. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  62739. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  62740. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  62741. */
  62742. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  62743. if (scene === void 0) { scene = null; }
  62744. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62745. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62746. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  62747. _this.name = name;
  62748. _this._engine = _this.getScene().getEngine();
  62749. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62750. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62751. _this._generateMipMaps = generateMipMaps;
  62752. if (options.getContext) {
  62753. _this._canvas = options;
  62754. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  62755. }
  62756. else {
  62757. _this._canvas = document.createElement("canvas");
  62758. if (options.width) {
  62759. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  62760. }
  62761. else {
  62762. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  62763. }
  62764. }
  62765. var textureSize = _this.getSize();
  62766. _this._canvas.width = textureSize.width;
  62767. _this._canvas.height = textureSize.height;
  62768. _this._context = _this._canvas.getContext("2d");
  62769. return _this;
  62770. }
  62771. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  62772. /**
  62773. * Gets the current state of canRescale
  62774. */
  62775. get: function () {
  62776. return true;
  62777. },
  62778. enumerable: true,
  62779. configurable: true
  62780. });
  62781. DynamicTexture.prototype._recreate = function (textureSize) {
  62782. this._canvas.width = textureSize.width;
  62783. this._canvas.height = textureSize.height;
  62784. this.releaseInternalTexture();
  62785. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  62786. };
  62787. /**
  62788. * Scales the texture
  62789. * @param ratio the scale factor to apply to both width and height
  62790. */
  62791. DynamicTexture.prototype.scale = function (ratio) {
  62792. var textureSize = this.getSize();
  62793. textureSize.width *= ratio;
  62794. textureSize.height *= ratio;
  62795. this._recreate(textureSize);
  62796. };
  62797. /**
  62798. * Resizes the texture
  62799. * @param width the new width
  62800. * @param height the new height
  62801. */
  62802. DynamicTexture.prototype.scaleTo = function (width, height) {
  62803. var textureSize = this.getSize();
  62804. textureSize.width = width;
  62805. textureSize.height = height;
  62806. this._recreate(textureSize);
  62807. };
  62808. /**
  62809. * Gets the context of the canvas used by the texture
  62810. * @returns the canvas context of the dynamic texture
  62811. */
  62812. DynamicTexture.prototype.getContext = function () {
  62813. return this._context;
  62814. };
  62815. /**
  62816. * Clears the texture
  62817. */
  62818. DynamicTexture.prototype.clear = function () {
  62819. var size = this.getSize();
  62820. this._context.fillRect(0, 0, size.width, size.height);
  62821. };
  62822. /**
  62823. * Updates the texture
  62824. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  62825. */
  62826. DynamicTexture.prototype.update = function (invertY) {
  62827. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  62828. };
  62829. /**
  62830. * Draws text onto the texture
  62831. * @param text defines the text to be drawn
  62832. * @param x defines the placement of the text from the left
  62833. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  62834. * @param font defines the font to be used with font-style, font-size, font-name
  62835. * @param color defines the color used for the text
  62836. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  62837. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  62838. * @param update defines whether texture is immediately update (default is true)
  62839. */
  62840. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  62841. if (update === void 0) { update = true; }
  62842. var size = this.getSize();
  62843. if (clearColor) {
  62844. this._context.fillStyle = clearColor;
  62845. this._context.fillRect(0, 0, size.width, size.height);
  62846. }
  62847. this._context.font = font;
  62848. if (x === null || x === undefined) {
  62849. var textSize = this._context.measureText(text);
  62850. x = (size.width - textSize.width) / 2;
  62851. }
  62852. if (y === null || y === undefined) {
  62853. var fontSize = parseInt((font.replace(/\D/g, '')));
  62854. ;
  62855. y = (size.height / 2) + (fontSize / 3.65);
  62856. }
  62857. this._context.fillStyle = color;
  62858. this._context.fillText(text, x, y);
  62859. if (update) {
  62860. this.update(invertY);
  62861. }
  62862. };
  62863. /**
  62864. * Clones the texture
  62865. * @returns the clone of the texture.
  62866. */
  62867. DynamicTexture.prototype.clone = function () {
  62868. var scene = this.getScene();
  62869. if (!scene) {
  62870. return this;
  62871. }
  62872. var textureSize = this.getSize();
  62873. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  62874. // Base texture
  62875. newTexture.hasAlpha = this.hasAlpha;
  62876. newTexture.level = this.level;
  62877. // Dynamic Texture
  62878. newTexture.wrapU = this.wrapU;
  62879. newTexture.wrapV = this.wrapV;
  62880. return newTexture;
  62881. };
  62882. /** @ignore */
  62883. DynamicTexture.prototype._rebuild = function () {
  62884. this.update();
  62885. };
  62886. return DynamicTexture;
  62887. }(BABYLON.Texture));
  62888. BABYLON.DynamicTexture = DynamicTexture;
  62889. })(BABYLON || (BABYLON = {}));
  62890. //# sourceMappingURL=babylon.dynamicTexture.js.map
  62891. "use strict";
  62892. var BABYLON;
  62893. (function (BABYLON) {
  62894. var VideoTexture = /** @class */ (function (_super) {
  62895. __extends(VideoTexture, _super);
  62896. /**
  62897. * Creates a video texture.
  62898. * Sample : https://doc.babylonjs.com/how_to/video_texture
  62899. * @param {string | null} name optional name, will detect from video source, if not defined
  62900. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  62901. * @param {BABYLON.Scene} scene is obviously the current scene.
  62902. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  62903. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  62904. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  62905. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  62906. */
  62907. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  62908. if (generateMipMaps === void 0) { generateMipMaps = false; }
  62909. if (invertY === void 0) { invertY = false; }
  62910. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62911. if (settings === void 0) { settings = {
  62912. autoPlay: true,
  62913. loop: true,
  62914. autoUpdateTexture: true,
  62915. }; }
  62916. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  62917. _this._createInternalTexture = function () {
  62918. if (_this._texture != null) {
  62919. return;
  62920. }
  62921. if (!_this._engine.needPOTTextures ||
  62922. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  62923. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62924. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62925. }
  62926. else {
  62927. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62928. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62929. _this._generateMipMaps = false;
  62930. }
  62931. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  62932. _this._texture.isReady = true;
  62933. _this._updateInternalTexture();
  62934. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  62935. _this.onLoadObservable.notifyObservers(_this);
  62936. }
  62937. };
  62938. _this.reset = function () {
  62939. if (_this._texture == null) {
  62940. return;
  62941. }
  62942. _this._texture.dispose();
  62943. _this._texture = null;
  62944. };
  62945. _this._updateInternalTexture = function (e) {
  62946. if (_this._texture == null || !_this._texture.isReady) {
  62947. return;
  62948. }
  62949. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  62950. return;
  62951. }
  62952. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  62953. };
  62954. _this._engine = _this.getScene().getEngine();
  62955. _this._generateMipMaps = generateMipMaps;
  62956. _this._samplingMode = samplingMode;
  62957. _this.autoUpdateTexture = settings.autoUpdateTexture;
  62958. _this.name = name || _this._getName(src);
  62959. _this.video = _this._getVideo(src);
  62960. if (settings.autoPlay !== undefined) {
  62961. _this.video.autoplay = settings.autoPlay;
  62962. }
  62963. if (settings.loop !== undefined) {
  62964. _this.video.loop = settings.loop;
  62965. }
  62966. _this.video.addEventListener("canplay", _this._createInternalTexture);
  62967. _this.video.addEventListener("paused", _this._updateInternalTexture);
  62968. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  62969. _this.video.addEventListener("emptied", _this.reset);
  62970. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  62971. _this._createInternalTexture();
  62972. }
  62973. return _this;
  62974. }
  62975. VideoTexture.prototype._getName = function (src) {
  62976. if (src instanceof HTMLVideoElement) {
  62977. return src.currentSrc;
  62978. }
  62979. if (typeof src === "object") {
  62980. return src.toString();
  62981. }
  62982. return src;
  62983. };
  62984. ;
  62985. VideoTexture.prototype._getVideo = function (src) {
  62986. if (src instanceof HTMLVideoElement) {
  62987. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  62988. return src;
  62989. }
  62990. var video = document.createElement("video");
  62991. if (typeof src === "string") {
  62992. BABYLON.Tools.SetCorsBehavior(src, video);
  62993. video.src = src;
  62994. }
  62995. else {
  62996. BABYLON.Tools.SetCorsBehavior(src[0], video);
  62997. src.forEach(function (url) {
  62998. var source = document.createElement("source");
  62999. source.src = url;
  63000. video.appendChild(source);
  63001. });
  63002. }
  63003. return video;
  63004. };
  63005. ;
  63006. /**
  63007. * Internal method to initiate `update`.
  63008. */
  63009. VideoTexture.prototype._rebuild = function () {
  63010. this.update();
  63011. };
  63012. /**
  63013. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63014. */
  63015. VideoTexture.prototype.update = function () {
  63016. if (!this.autoUpdateTexture) {
  63017. // Expecting user to call `updateTexture` manually
  63018. return;
  63019. }
  63020. this.updateTexture(true);
  63021. };
  63022. /**
  63023. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  63024. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  63025. */
  63026. VideoTexture.prototype.updateTexture = function (isVisible) {
  63027. if (!isVisible) {
  63028. return;
  63029. }
  63030. if (this.video.paused) {
  63031. return;
  63032. }
  63033. this._updateInternalTexture();
  63034. };
  63035. /**
  63036. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63037. * @param url New url.
  63038. */
  63039. VideoTexture.prototype.updateURL = function (url) {
  63040. this.video.src = url;
  63041. };
  63042. VideoTexture.prototype.dispose = function () {
  63043. _super.prototype.dispose.call(this);
  63044. this.video.removeEventListener("canplay", this._createInternalTexture);
  63045. this.video.removeEventListener("paused", this._updateInternalTexture);
  63046. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63047. this.video.removeEventListener("emptied", this.reset);
  63048. this.video.pause();
  63049. };
  63050. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63051. var video = document.createElement("video");
  63052. var constraintsDeviceId;
  63053. if (constraints && constraints.deviceId) {
  63054. constraintsDeviceId = {
  63055. exact: constraints.deviceId,
  63056. };
  63057. }
  63058. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  63059. if (navigator.mediaDevices) {
  63060. navigator.mediaDevices.getUserMedia({ video: constraints })
  63061. .then(function (stream) {
  63062. if (video.mozSrcObject !== undefined) {
  63063. // hack for Firefox < 19
  63064. video.mozSrcObject = stream;
  63065. }
  63066. else {
  63067. video.srcObject = stream;
  63068. }
  63069. var onPlaying = function () {
  63070. if (onReady) {
  63071. onReady(new VideoTexture("video", video, scene, true, true));
  63072. }
  63073. video.removeEventListener("playing", onPlaying);
  63074. };
  63075. video.addEventListener("playing", onPlaying);
  63076. video.play();
  63077. })
  63078. .catch(function (err) {
  63079. BABYLON.Tools.Error(err.name);
  63080. });
  63081. }
  63082. else {
  63083. navigator.getUserMedia =
  63084. navigator.getUserMedia ||
  63085. navigator.webkitGetUserMedia ||
  63086. navigator.mozGetUserMedia ||
  63087. navigator.msGetUserMedia;
  63088. if (navigator.getUserMedia) {
  63089. navigator.getUserMedia({
  63090. video: {
  63091. deviceId: constraintsDeviceId,
  63092. width: {
  63093. min: (constraints && constraints.minWidth) || 256,
  63094. max: (constraints && constraints.maxWidth) || 640,
  63095. },
  63096. height: {
  63097. min: (constraints && constraints.minHeight) || 256,
  63098. max: (constraints && constraints.maxHeight) || 480,
  63099. },
  63100. },
  63101. }, function (stream) {
  63102. if (video.mozSrcObject !== undefined) {
  63103. // hack for Firefox < 19
  63104. video.mozSrcObject = stream;
  63105. }
  63106. else {
  63107. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  63108. }
  63109. video.play();
  63110. if (onReady) {
  63111. onReady(new VideoTexture("video", video, scene, true, true));
  63112. }
  63113. }, function (e) {
  63114. BABYLON.Tools.Error(e.name);
  63115. });
  63116. }
  63117. }
  63118. };
  63119. return VideoTexture;
  63120. }(BABYLON.Texture));
  63121. BABYLON.VideoTexture = VideoTexture;
  63122. })(BABYLON || (BABYLON = {}));
  63123. //# sourceMappingURL=babylon.videoTexture.js.map
  63124. "use strict";
  63125. var BABYLON;
  63126. (function (BABYLON) {
  63127. var RawTexture = /** @class */ (function (_super) {
  63128. __extends(RawTexture, _super);
  63129. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  63130. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63131. if (invertY === void 0) { invertY = false; }
  63132. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63133. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63134. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63135. _this.format = format;
  63136. _this._engine = scene.getEngine();
  63137. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  63138. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63139. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63140. return _this;
  63141. }
  63142. RawTexture.prototype.update = function (data) {
  63143. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  63144. };
  63145. // Statics
  63146. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63147. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63148. if (invertY === void 0) { invertY = false; }
  63149. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63150. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  63151. };
  63152. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63153. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63154. if (invertY === void 0) { invertY = false; }
  63155. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63156. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63157. };
  63158. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63159. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63160. if (invertY === void 0) { invertY = false; }
  63161. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63162. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63163. };
  63164. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63165. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63166. if (invertY === void 0) { invertY = false; }
  63167. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63168. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63169. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  63170. };
  63171. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63172. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63173. if (invertY === void 0) { invertY = false; }
  63174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63175. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63176. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  63177. };
  63178. return RawTexture;
  63179. }(BABYLON.Texture));
  63180. BABYLON.RawTexture = RawTexture;
  63181. })(BABYLON || (BABYLON = {}));
  63182. //# sourceMappingURL=babylon.rawTexture.js.map
  63183. "use strict";
  63184. var BABYLON;
  63185. (function (BABYLON) {
  63186. /**
  63187. * Class used to store 3D textures containing user data
  63188. */
  63189. var RawTexture3D = /** @class */ (function (_super) {
  63190. __extends(RawTexture3D, _super);
  63191. /**
  63192. * Create a new RawTexture3D
  63193. * @param data defines the data of the texture
  63194. * @param width defines the width of the texture
  63195. * @param height defines the height of the texture
  63196. * @param depth defines the depth of the texture
  63197. * @param format defines the texture format to use
  63198. * @param scene defines the hosting scene
  63199. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  63200. * @param invertY defines if texture must be stored with Y axis inverted
  63201. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  63202. */
  63203. function RawTexture3D(data, width, height, depth,
  63204. /** Gets or sets the texture format to use*/
  63205. format, scene, generateMipMaps, invertY, samplingMode) {
  63206. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63207. if (invertY === void 0) { invertY = false; }
  63208. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63209. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63210. _this.format = format;
  63211. _this._engine = scene.getEngine();
  63212. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  63213. _this.is3D = true;
  63214. return _this;
  63215. }
  63216. /**
  63217. * Update the texture with new data
  63218. * @param data defines the data to store in the texture
  63219. */
  63220. RawTexture3D.prototype.update = function (data) {
  63221. if (!this._texture) {
  63222. return;
  63223. }
  63224. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  63225. };
  63226. return RawTexture3D;
  63227. }(BABYLON.Texture));
  63228. BABYLON.RawTexture3D = RawTexture3D;
  63229. })(BABYLON || (BABYLON = {}));
  63230. //# sourceMappingURL=babylon.rawTexture3D.js.map
  63231. "use strict";
  63232. var BABYLON;
  63233. (function (BABYLON) {
  63234. /**
  63235. * PostProcess can be used to apply a shader to a texture after it has been rendered
  63236. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  63237. */
  63238. var PostProcess = /** @class */ (function () {
  63239. /**
  63240. * Creates a new instance PostProcess
  63241. * @param name The name of the PostProcess.
  63242. * @param fragmentUrl The url of the fragment shader to be used.
  63243. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  63244. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  63245. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  63246. * @param camera The camera to apply the render pass to.
  63247. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  63248. * @param engine The engine which the post process will be applied. (default: current engine)
  63249. * @param reusable If the post process can be reused on the same frame. (default: false)
  63250. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  63251. * @param textureType Type of textures used when performing the post process. (default: 0)
  63252. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  63253. * @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
  63254. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  63255. */
  63256. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  63257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  63258. if (defines === void 0) { defines = null; }
  63259. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63260. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  63261. if (blockCompilation === void 0) { blockCompilation = false; }
  63262. this.name = name;
  63263. /**
  63264. * Width of the texture to apply the post process on
  63265. */
  63266. this.width = -1;
  63267. /**
  63268. * Height of the texture to apply the post process on
  63269. */
  63270. this.height = -1;
  63271. /**
  63272. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  63273. */
  63274. this._outputTexture = null;
  63275. /**
  63276. * If the buffer needs to be cleared before applying the post process. (default: true)
  63277. * Should be set to false if shader will overwrite all previous pixels.
  63278. */
  63279. this.autoClear = true;
  63280. /**
  63281. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  63282. */
  63283. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  63284. /**
  63285. * Animations to be used for the post processing
  63286. */
  63287. this.animations = new Array();
  63288. /**
  63289. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  63290. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  63291. */
  63292. this.enablePixelPerfectMode = false;
  63293. /**
  63294. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  63295. */
  63296. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  63297. /**
  63298. * Force textures to be a power of two (default: false)
  63299. */
  63300. this.alwaysForcePOT = false;
  63301. /**
  63302. * Number of sample textures (default: 1)
  63303. */
  63304. this.samples = 1;
  63305. /**
  63306. * Modify the scale of the post process to be the same as the viewport (default: false)
  63307. */
  63308. this.adaptScaleToCurrentViewport = false;
  63309. this._reusable = false;
  63310. /**
  63311. * Smart array of input and output textures for the post process.
  63312. */
  63313. this._textures = new BABYLON.SmartArray(2);
  63314. /**
  63315. * The index in _textures that corresponds to the output texture.
  63316. */
  63317. this._currentRenderTextureInd = 0;
  63318. this._scaleRatio = new BABYLON.Vector2(1, 1);
  63319. this._texelSize = BABYLON.Vector2.Zero();
  63320. // Events
  63321. /**
  63322. * An event triggered when the postprocess is activated.
  63323. */
  63324. this.onActivateObservable = new BABYLON.Observable();
  63325. /**
  63326. * An event triggered when the postprocess changes its size.
  63327. */
  63328. this.onSizeChangedObservable = new BABYLON.Observable();
  63329. /**
  63330. * An event triggered when the postprocess applies its effect.
  63331. */
  63332. this.onApplyObservable = new BABYLON.Observable();
  63333. /**
  63334. * An event triggered before rendering the postprocess
  63335. */
  63336. this.onBeforeRenderObservable = new BABYLON.Observable();
  63337. /**
  63338. * An event triggered after rendering the postprocess
  63339. */
  63340. this.onAfterRenderObservable = new BABYLON.Observable();
  63341. if (camera != null) {
  63342. this._camera = camera;
  63343. this._scene = camera.getScene();
  63344. camera.attachPostProcess(this);
  63345. this._engine = this._scene.getEngine();
  63346. this._scene.postProcesses.push(this);
  63347. }
  63348. else if (engine) {
  63349. this._engine = engine;
  63350. this._engine.postProcesses.push(this);
  63351. }
  63352. this._options = options;
  63353. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  63354. this._reusable = reusable || false;
  63355. this._textureType = textureType;
  63356. this._samplers = samplers || [];
  63357. this._samplers.push("textureSampler");
  63358. this._fragmentUrl = fragmentUrl;
  63359. this._vertexUrl = vertexUrl;
  63360. this._parameters = parameters || [];
  63361. this._parameters.push("scale");
  63362. this._indexParameters = indexParameters;
  63363. if (!blockCompilation) {
  63364. this.updateEffect(defines);
  63365. }
  63366. }
  63367. Object.defineProperty(PostProcess.prototype, "onActivate", {
  63368. /**
  63369. * A function that is added to the onActivateObservable
  63370. */
  63371. set: function (callback) {
  63372. if (this._onActivateObserver) {
  63373. this.onActivateObservable.remove(this._onActivateObserver);
  63374. }
  63375. if (callback) {
  63376. this._onActivateObserver = this.onActivateObservable.add(callback);
  63377. }
  63378. },
  63379. enumerable: true,
  63380. configurable: true
  63381. });
  63382. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  63383. /**
  63384. * A function that is added to the onSizeChangedObservable
  63385. */
  63386. set: function (callback) {
  63387. if (this._onSizeChangedObserver) {
  63388. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  63389. }
  63390. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  63391. },
  63392. enumerable: true,
  63393. configurable: true
  63394. });
  63395. Object.defineProperty(PostProcess.prototype, "onApply", {
  63396. /**
  63397. * A function that is added to the onApplyObservable
  63398. */
  63399. set: function (callback) {
  63400. if (this._onApplyObserver) {
  63401. this.onApplyObservable.remove(this._onApplyObserver);
  63402. }
  63403. this._onApplyObserver = this.onApplyObservable.add(callback);
  63404. },
  63405. enumerable: true,
  63406. configurable: true
  63407. });
  63408. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  63409. /**
  63410. * A function that is added to the onBeforeRenderObservable
  63411. */
  63412. set: function (callback) {
  63413. if (this._onBeforeRenderObserver) {
  63414. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63415. }
  63416. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63417. },
  63418. enumerable: true,
  63419. configurable: true
  63420. });
  63421. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  63422. /**
  63423. * A function that is added to the onAfterRenderObservable
  63424. */
  63425. set: function (callback) {
  63426. if (this._onAfterRenderObserver) {
  63427. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63428. }
  63429. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63430. },
  63431. enumerable: true,
  63432. configurable: true
  63433. });
  63434. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  63435. /**
  63436. * 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
  63437. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  63438. */
  63439. get: function () {
  63440. return this._textures.data[this._currentRenderTextureInd];
  63441. },
  63442. set: function (value) {
  63443. this._forcedOutputTexture = value;
  63444. },
  63445. enumerable: true,
  63446. configurable: true
  63447. });
  63448. /**
  63449. * Gets the camera which post process is applied to.
  63450. * @returns The camera the post process is applied to.
  63451. */
  63452. PostProcess.prototype.getCamera = function () {
  63453. return this._camera;
  63454. };
  63455. Object.defineProperty(PostProcess.prototype, "texelSize", {
  63456. /**
  63457. * Gets the texel size of the postprocess.
  63458. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  63459. */
  63460. get: function () {
  63461. if (this._shareOutputWithPostProcess) {
  63462. return this._shareOutputWithPostProcess.texelSize;
  63463. }
  63464. if (this._forcedOutputTexture) {
  63465. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  63466. }
  63467. return this._texelSize;
  63468. },
  63469. enumerable: true,
  63470. configurable: true
  63471. });
  63472. /**
  63473. * Gets the engine which this post process belongs to.
  63474. * @returns The engine the post process was enabled with.
  63475. */
  63476. PostProcess.prototype.getEngine = function () {
  63477. return this._engine;
  63478. };
  63479. /**
  63480. * The effect that is created when initializing the post process.
  63481. * @returns The created effect corrisponding the the postprocess.
  63482. */
  63483. PostProcess.prototype.getEffect = function () {
  63484. return this._effect;
  63485. };
  63486. /**
  63487. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  63488. * @param postProcess The post process to share the output with.
  63489. * @returns This post process.
  63490. */
  63491. PostProcess.prototype.shareOutputWith = function (postProcess) {
  63492. this._disposeTextures();
  63493. this._shareOutputWithPostProcess = postProcess;
  63494. return this;
  63495. };
  63496. /**
  63497. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  63498. * This should be called if the post process that shares output with this post process is disabled/disposed.
  63499. */
  63500. PostProcess.prototype.useOwnOutput = function () {
  63501. if (this._textures.length == 0) {
  63502. this._textures = new BABYLON.SmartArray(2);
  63503. }
  63504. this._shareOutputWithPostProcess = null;
  63505. };
  63506. /**
  63507. * Updates the effect with the current post process compile time values and recompiles the shader.
  63508. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  63509. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  63510. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  63511. * @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
  63512. * @param onCompiled Called when the shader has been compiled.
  63513. * @param onError Called if there is an error when compiling a shader.
  63514. */
  63515. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  63516. if (defines === void 0) { defines = null; }
  63517. if (uniforms === void 0) { uniforms = null; }
  63518. if (samplers === void 0) { samplers = null; }
  63519. 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);
  63520. };
  63521. /**
  63522. * The post process is reusable if it can be used multiple times within one frame.
  63523. * @returns If the post process is reusable
  63524. */
  63525. PostProcess.prototype.isReusable = function () {
  63526. return this._reusable;
  63527. };
  63528. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  63529. PostProcess.prototype.markTextureDirty = function () {
  63530. this.width = -1;
  63531. };
  63532. /**
  63533. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  63534. * 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.
  63535. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  63536. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  63537. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  63538. * @returns The target texture that was bound to be written to.
  63539. */
  63540. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  63541. var _this = this;
  63542. if (sourceTexture === void 0) { sourceTexture = null; }
  63543. camera = camera || this._camera;
  63544. var scene = camera.getScene();
  63545. var engine = scene.getEngine();
  63546. var maxSize = engine.getCaps().maxTextureSize;
  63547. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  63548. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  63549. // 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
  63550. var webVRCamera = camera.parent;
  63551. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  63552. requiredWidth /= 2;
  63553. }
  63554. var desiredWidth = (this._options.width || requiredWidth);
  63555. var desiredHeight = this._options.height || requiredHeight;
  63556. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  63557. if (this.adaptScaleToCurrentViewport) {
  63558. var currentViewport = engine.currentViewport;
  63559. if (currentViewport) {
  63560. desiredWidth *= currentViewport.width;
  63561. desiredHeight *= currentViewport.height;
  63562. }
  63563. }
  63564. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  63565. if (!this._options.width) {
  63566. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  63567. }
  63568. if (!this._options.height) {
  63569. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  63570. }
  63571. }
  63572. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  63573. if (this._textures.length > 0) {
  63574. for (var i = 0; i < this._textures.length; i++) {
  63575. this._engine._releaseTexture(this._textures.data[i]);
  63576. }
  63577. this._textures.reset();
  63578. }
  63579. this.width = desiredWidth;
  63580. this.height = desiredHeight;
  63581. var textureSize = { width: this.width, height: this.height };
  63582. var textureOptions = {
  63583. generateMipMaps: false,
  63584. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  63585. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  63586. samplingMode: this.renderTargetSamplingMode,
  63587. type: this._textureType
  63588. };
  63589. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63590. if (this._reusable) {
  63591. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63592. }
  63593. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  63594. this.onSizeChangedObservable.notifyObservers(this);
  63595. }
  63596. this._textures.forEach(function (texture) {
  63597. if (texture.samples !== _this.samples) {
  63598. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  63599. }
  63600. });
  63601. }
  63602. var target;
  63603. if (this._shareOutputWithPostProcess) {
  63604. target = this._shareOutputWithPostProcess.inputTexture;
  63605. }
  63606. else if (this._forcedOutputTexture) {
  63607. target = this._forcedOutputTexture;
  63608. this.width = this._forcedOutputTexture.width;
  63609. this.height = this._forcedOutputTexture.height;
  63610. }
  63611. else {
  63612. target = this.inputTexture;
  63613. }
  63614. // Bind the input of this post process to be used as the output of the previous post process.
  63615. if (this.enablePixelPerfectMode) {
  63616. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  63617. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  63618. }
  63619. else {
  63620. this._scaleRatio.copyFromFloats(1, 1);
  63621. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  63622. }
  63623. this.onActivateObservable.notifyObservers(camera);
  63624. // Clear
  63625. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  63626. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  63627. }
  63628. if (this._reusable) {
  63629. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  63630. }
  63631. return target;
  63632. };
  63633. Object.defineProperty(PostProcess.prototype, "isSupported", {
  63634. /**
  63635. * If the post process is supported.
  63636. */
  63637. get: function () {
  63638. return this._effect.isSupported;
  63639. },
  63640. enumerable: true,
  63641. configurable: true
  63642. });
  63643. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  63644. /**
  63645. * The aspect ratio of the output texture.
  63646. */
  63647. get: function () {
  63648. if (this._shareOutputWithPostProcess) {
  63649. return this._shareOutputWithPostProcess.aspectRatio;
  63650. }
  63651. if (this._forcedOutputTexture) {
  63652. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  63653. }
  63654. return this.width / this.height;
  63655. },
  63656. enumerable: true,
  63657. configurable: true
  63658. });
  63659. /**
  63660. * Get a value indicating if the post-process is ready to be used
  63661. * @returns true if the post-process is ready (shader is compiled)
  63662. */
  63663. PostProcess.prototype.isReady = function () {
  63664. return this._effect && this._effect.isReady();
  63665. };
  63666. /**
  63667. * Binds all textures and uniforms to the shader, this will be run on every pass.
  63668. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  63669. */
  63670. PostProcess.prototype.apply = function () {
  63671. // Check
  63672. if (!this._effect || !this._effect.isReady())
  63673. return null;
  63674. // States
  63675. this._engine.enableEffect(this._effect);
  63676. this._engine.setState(false);
  63677. this._engine.setDepthBuffer(false);
  63678. this._engine.setDepthWrite(false);
  63679. // Alpha
  63680. this._engine.setAlphaMode(this.alphaMode);
  63681. if (this.alphaConstants) {
  63682. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  63683. }
  63684. // Bind the output texture of the preivous post process as the input to this post process.
  63685. var source;
  63686. if (this._shareOutputWithPostProcess) {
  63687. source = this._shareOutputWithPostProcess.inputTexture;
  63688. }
  63689. else if (this._forcedOutputTexture) {
  63690. source = this._forcedOutputTexture;
  63691. }
  63692. else {
  63693. source = this.inputTexture;
  63694. }
  63695. this._effect._bindTexture("textureSampler", source);
  63696. // Parameters
  63697. this._effect.setVector2("scale", this._scaleRatio);
  63698. this.onApplyObservable.notifyObservers(this._effect);
  63699. return this._effect;
  63700. };
  63701. PostProcess.prototype._disposeTextures = function () {
  63702. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  63703. return;
  63704. }
  63705. if (this._textures.length > 0) {
  63706. for (var i = 0; i < this._textures.length; i++) {
  63707. this._engine._releaseTexture(this._textures.data[i]);
  63708. }
  63709. }
  63710. this._textures.dispose();
  63711. };
  63712. /**
  63713. * Disposes the post process.
  63714. * @param camera The camera to dispose the post process on.
  63715. */
  63716. PostProcess.prototype.dispose = function (camera) {
  63717. camera = camera || this._camera;
  63718. this._disposeTextures();
  63719. if (this._scene) {
  63720. var index_1 = this._scene.postProcesses.indexOf(this);
  63721. if (index_1 !== -1) {
  63722. this._scene.postProcesses.splice(index_1, 1);
  63723. }
  63724. }
  63725. else {
  63726. var index_2 = this._engine.postProcesses.indexOf(this);
  63727. if (index_2 !== -1) {
  63728. this._engine.postProcesses.splice(index_2, 1);
  63729. }
  63730. }
  63731. if (!camera) {
  63732. return;
  63733. }
  63734. camera.detachPostProcess(this);
  63735. var index = camera._postProcesses.indexOf(this);
  63736. if (index === 0 && camera._postProcesses.length > 0) {
  63737. var firstPostProcess = this._camera._getFirstPostProcess();
  63738. if (firstPostProcess) {
  63739. firstPostProcess.markTextureDirty();
  63740. }
  63741. }
  63742. this.onActivateObservable.clear();
  63743. this.onAfterRenderObservable.clear();
  63744. this.onApplyObservable.clear();
  63745. this.onBeforeRenderObservable.clear();
  63746. this.onSizeChangedObservable.clear();
  63747. };
  63748. return PostProcess;
  63749. }());
  63750. BABYLON.PostProcess = PostProcess;
  63751. })(BABYLON || (BABYLON = {}));
  63752. //# sourceMappingURL=babylon.postProcess.js.map
  63753. "use strict";
  63754. var BABYLON;
  63755. (function (BABYLON) {
  63756. var PassPostProcess = /** @class */ (function (_super) {
  63757. __extends(PassPostProcess, _super);
  63758. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  63759. if (camera === void 0) { camera = null; }
  63760. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63761. if (blockCompilation === void 0) { blockCompilation = false; }
  63762. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  63763. }
  63764. return PassPostProcess;
  63765. }(BABYLON.PostProcess));
  63766. BABYLON.PassPostProcess = PassPostProcess;
  63767. })(BABYLON || (BABYLON = {}));
  63768. //# sourceMappingURL=babylon.passPostProcess.js.map
  63769. "use strict";
  63770. var __assign = (this && this.__assign) || Object.assign || function(t) {
  63771. for (var s, i = 1, n = arguments.length; i < n; i++) {
  63772. s = arguments[i];
  63773. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  63774. t[p] = s[p];
  63775. }
  63776. return t;
  63777. };
  63778. var BABYLON;
  63779. (function (BABYLON) {
  63780. /**
  63781. * Default implementation IShadowGenerator.
  63782. * This is the main object responsible of generating shadows in the framework.
  63783. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  63784. */
  63785. var ShadowGenerator = /** @class */ (function () {
  63786. /**
  63787. * Creates a ShadowGenerator object.
  63788. * A ShadowGenerator is the required tool to use the shadows.
  63789. * Each light casting shadows needs to use its own ShadowGenerator.
  63790. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  63791. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  63792. * @param light The light object generating the shadows.
  63793. * @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.
  63794. */
  63795. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  63796. this._bias = 0.00005;
  63797. this._normalBias = 0;
  63798. this._blurBoxOffset = 1;
  63799. this._blurScale = 2;
  63800. this._blurKernel = 1;
  63801. this._useKernelBlur = false;
  63802. this._filter = ShadowGenerator.FILTER_NONE;
  63803. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  63804. this._contactHardeningLightSizeUVRatio = 0.1;
  63805. this._darkness = 0;
  63806. this._transparencyShadow = false;
  63807. /**
  63808. * Controls the extent to which the shadows fade out at the edge of the frustum
  63809. * Used only by directionals and spots
  63810. */
  63811. this.frustumEdgeFalloff = 0;
  63812. /**
  63813. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  63814. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  63815. * It might on the other hand introduce peter panning.
  63816. */
  63817. this.forceBackFacesOnly = false;
  63818. this._lightDirection = BABYLON.Vector3.Zero();
  63819. this._viewMatrix = BABYLON.Matrix.Zero();
  63820. this._projectionMatrix = BABYLON.Matrix.Zero();
  63821. this._transformMatrix = BABYLON.Matrix.Zero();
  63822. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  63823. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  63824. this._currentFaceIndex = 0;
  63825. this._currentFaceIndexCache = 0;
  63826. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  63827. this._mapSize = mapSize;
  63828. this._light = light;
  63829. this._scene = light.getScene();
  63830. light._shadowGenerator = this;
  63831. // Texture type fallback from float to int if not supported.
  63832. var caps = this._scene.getEngine().getCaps();
  63833. if (!useFullFloatFirst) {
  63834. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  63835. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63836. }
  63837. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  63838. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63839. }
  63840. else {
  63841. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63842. }
  63843. }
  63844. else {
  63845. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  63846. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63847. }
  63848. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  63849. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63850. }
  63851. else {
  63852. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63853. }
  63854. }
  63855. this._initializeGenerator();
  63856. this._applyFilterValues();
  63857. }
  63858. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  63859. /**
  63860. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  63861. */
  63862. get: function () {
  63863. return this._bias;
  63864. },
  63865. /**
  63866. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  63867. */
  63868. set: function (bias) {
  63869. this._bias = bias;
  63870. },
  63871. enumerable: true,
  63872. configurable: true
  63873. });
  63874. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  63875. /**
  63876. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  63877. */
  63878. get: function () {
  63879. return this._normalBias;
  63880. },
  63881. /**
  63882. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  63883. */
  63884. set: function (normalBias) {
  63885. this._normalBias = normalBias;
  63886. },
  63887. enumerable: true,
  63888. configurable: true
  63889. });
  63890. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  63891. /**
  63892. * Gets the blur box offset: offset applied during the blur pass.
  63893. * Only usefull if useKernelBlur = false
  63894. */
  63895. get: function () {
  63896. return this._blurBoxOffset;
  63897. },
  63898. /**
  63899. * Sets the blur box offset: offset applied during the blur pass.
  63900. * Only usefull if useKernelBlur = false
  63901. */
  63902. set: function (value) {
  63903. if (this._blurBoxOffset === value) {
  63904. return;
  63905. }
  63906. this._blurBoxOffset = value;
  63907. this._disposeBlurPostProcesses();
  63908. },
  63909. enumerable: true,
  63910. configurable: true
  63911. });
  63912. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  63913. /**
  63914. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  63915. * 2 means half of the size.
  63916. */
  63917. get: function () {
  63918. return this._blurScale;
  63919. },
  63920. /**
  63921. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  63922. * 2 means half of the size.
  63923. */
  63924. set: function (value) {
  63925. if (this._blurScale === value) {
  63926. return;
  63927. }
  63928. this._blurScale = value;
  63929. this._disposeBlurPostProcesses();
  63930. },
  63931. enumerable: true,
  63932. configurable: true
  63933. });
  63934. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  63935. /**
  63936. * Gets the blur kernel: kernel size of the blur pass.
  63937. * Only usefull if useKernelBlur = true
  63938. */
  63939. get: function () {
  63940. return this._blurKernel;
  63941. },
  63942. /**
  63943. * Sets the blur kernel: kernel size of the blur pass.
  63944. * Only usefull if useKernelBlur = true
  63945. */
  63946. set: function (value) {
  63947. if (this._blurKernel === value) {
  63948. return;
  63949. }
  63950. this._blurKernel = value;
  63951. this._disposeBlurPostProcesses();
  63952. },
  63953. enumerable: true,
  63954. configurable: true
  63955. });
  63956. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  63957. /**
  63958. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  63959. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  63960. */
  63961. get: function () {
  63962. return this._useKernelBlur;
  63963. },
  63964. /**
  63965. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  63966. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  63967. */
  63968. set: function (value) {
  63969. if (this._useKernelBlur === value) {
  63970. return;
  63971. }
  63972. this._useKernelBlur = value;
  63973. this._disposeBlurPostProcesses();
  63974. },
  63975. enumerable: true,
  63976. configurable: true
  63977. });
  63978. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  63979. /**
  63980. * Gets the depth scale used in ESM mode.
  63981. */
  63982. get: function () {
  63983. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  63984. },
  63985. /**
  63986. * Sets the depth scale used in ESM mode.
  63987. * This can override the scale stored on the light.
  63988. */
  63989. set: function (value) {
  63990. this._depthScale = value;
  63991. },
  63992. enumerable: true,
  63993. configurable: true
  63994. });
  63995. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  63996. /**
  63997. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  63998. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  63999. */
  64000. get: function () {
  64001. return this._filter;
  64002. },
  64003. /**
  64004. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  64005. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64006. */
  64007. set: function (value) {
  64008. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  64009. if (this._light.needCube()) {
  64010. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64011. this.useExponentialShadowMap = true;
  64012. return;
  64013. }
  64014. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64015. this.useCloseExponentialShadowMap = true;
  64016. return;
  64017. }
  64018. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64019. this.usePoissonSampling = true;
  64020. return;
  64021. }
  64022. }
  64023. // Weblg1 fallback for PCF.
  64024. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64025. if (this._scene.getEngine().webGLVersion === 1) {
  64026. this.usePoissonSampling = true;
  64027. return;
  64028. }
  64029. }
  64030. if (this._filter === value) {
  64031. return;
  64032. }
  64033. this._filter = value;
  64034. this._disposeBlurPostProcesses();
  64035. this._applyFilterValues();
  64036. this._light._markMeshesAsLightDirty();
  64037. },
  64038. enumerable: true,
  64039. configurable: true
  64040. });
  64041. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  64042. /**
  64043. * Gets if the current filter is set to Poisson Sampling.
  64044. */
  64045. get: function () {
  64046. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  64047. },
  64048. /**
  64049. * Sets the current filter to Poisson Sampling.
  64050. */
  64051. set: function (value) {
  64052. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  64053. return;
  64054. }
  64055. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  64056. },
  64057. enumerable: true,
  64058. configurable: true
  64059. });
  64060. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  64061. /**
  64062. * Gets if the current filter is set to VSM.
  64063. * DEPRECATED. Should use useExponentialShadowMap instead.
  64064. */
  64065. get: function () {
  64066. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64067. return this.useExponentialShadowMap;
  64068. },
  64069. /**
  64070. * Sets the current filter is to VSM.
  64071. * DEPRECATED. Should use useExponentialShadowMap instead.
  64072. */
  64073. set: function (value) {
  64074. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64075. this.useExponentialShadowMap = value;
  64076. },
  64077. enumerable: true,
  64078. configurable: true
  64079. });
  64080. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  64081. /**
  64082. * Gets if the current filter is set to blurred VSM.
  64083. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64084. */
  64085. get: function () {
  64086. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64087. return this.useBlurExponentialShadowMap;
  64088. },
  64089. /**
  64090. * Sets the current filter is to blurred VSM.
  64091. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64092. */
  64093. set: function (value) {
  64094. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64095. this.useBlurExponentialShadowMap = value;
  64096. },
  64097. enumerable: true,
  64098. configurable: true
  64099. });
  64100. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  64101. /**
  64102. * Gets if the current filter is set to ESM.
  64103. */
  64104. get: function () {
  64105. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  64106. },
  64107. /**
  64108. * Sets the current filter is to ESM.
  64109. */
  64110. set: function (value) {
  64111. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  64112. return;
  64113. }
  64114. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64115. },
  64116. enumerable: true,
  64117. configurable: true
  64118. });
  64119. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  64120. /**
  64121. * Gets if the current filter is set to filtered ESM.
  64122. */
  64123. get: function () {
  64124. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  64125. },
  64126. /**
  64127. * Gets if the current filter is set to filtered ESM.
  64128. */
  64129. set: function (value) {
  64130. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64131. return;
  64132. }
  64133. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64134. },
  64135. enumerable: true,
  64136. configurable: true
  64137. });
  64138. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  64139. /**
  64140. * Gets if the current filter is set to "close ESM" (using the inverse of the
  64141. * exponential to prevent steep falloff artifacts).
  64142. */
  64143. get: function () {
  64144. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  64145. },
  64146. /**
  64147. * Sets the current filter to "close ESM" (using the inverse of the
  64148. * exponential to prevent steep falloff artifacts).
  64149. */
  64150. set: function (value) {
  64151. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  64152. return;
  64153. }
  64154. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64155. },
  64156. enumerable: true,
  64157. configurable: true
  64158. });
  64159. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  64160. /**
  64161. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  64162. * exponential to prevent steep falloff artifacts).
  64163. */
  64164. get: function () {
  64165. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  64166. },
  64167. /**
  64168. * Sets the current filter to filtered "close ESM" (using the inverse of the
  64169. * exponential to prevent steep falloff artifacts).
  64170. */
  64171. set: function (value) {
  64172. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64173. return;
  64174. }
  64175. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64176. },
  64177. enumerable: true,
  64178. configurable: true
  64179. });
  64180. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  64181. /**
  64182. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  64183. */
  64184. get: function () {
  64185. return this.filter === ShadowGenerator.FILTER_PCF;
  64186. },
  64187. /**
  64188. * Sets the current filter to "PCF" (percentage closer filtering).
  64189. */
  64190. set: function (value) {
  64191. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  64192. return;
  64193. }
  64194. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  64195. },
  64196. enumerable: true,
  64197. configurable: true
  64198. });
  64199. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  64200. /**
  64201. * Gets the PCF or PCSS Quality.
  64202. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  64203. */
  64204. get: function () {
  64205. return this._filteringQuality;
  64206. },
  64207. /**
  64208. * Sets the PCF or PCSS Quality.
  64209. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  64210. */
  64211. set: function (filteringQuality) {
  64212. this._filteringQuality = filteringQuality;
  64213. },
  64214. enumerable: true,
  64215. configurable: true
  64216. });
  64217. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  64218. /**
  64219. * Gets if the current filter is set to "PCSS" (contact hardening).
  64220. */
  64221. get: function () {
  64222. return this.filter === ShadowGenerator.FILTER_PCSS;
  64223. },
  64224. /**
  64225. * Sets the current filter to "PCSS" (contact hardening).
  64226. */
  64227. set: function (value) {
  64228. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  64229. return;
  64230. }
  64231. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  64232. },
  64233. enumerable: true,
  64234. configurable: true
  64235. });
  64236. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  64237. /**
  64238. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  64239. * Using a ratio helps keeping shape stability independently of the map size.
  64240. *
  64241. * It does not account for the light projection as it was having too much
  64242. * instability during the light setup or during light position changes.
  64243. *
  64244. * Only valid if useContactHardeningShadow is true.
  64245. */
  64246. get: function () {
  64247. return this._contactHardeningLightSizeUVRatio;
  64248. },
  64249. /**
  64250. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  64251. * Using a ratio helps keeping shape stability independently of the map size.
  64252. *
  64253. * It does not account for the light projection as it was having too much
  64254. * instability during the light setup or during light position changes.
  64255. *
  64256. * Only valid if useContactHardeningShadow is true.
  64257. */
  64258. set: function (contactHardeningLightSizeUVRatio) {
  64259. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  64260. },
  64261. enumerable: true,
  64262. configurable: true
  64263. });
  64264. /**
  64265. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  64266. * 0 means strongest and 1 would means no shadow.
  64267. * @returns the darkness.
  64268. */
  64269. ShadowGenerator.prototype.getDarkness = function () {
  64270. return this._darkness;
  64271. };
  64272. /**
  64273. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  64274. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  64275. * @returns the shadow generator allowing fluent coding.
  64276. */
  64277. ShadowGenerator.prototype.setDarkness = function (darkness) {
  64278. if (darkness >= 1.0)
  64279. this._darkness = 1.0;
  64280. else if (darkness <= 0.0)
  64281. this._darkness = 0.0;
  64282. else
  64283. this._darkness = darkness;
  64284. return this;
  64285. };
  64286. /**
  64287. * Sets the ability to have transparent shadow (boolean).
  64288. * @param transparent True if transparent else False
  64289. * @returns the shadow generator allowing fluent coding
  64290. */
  64291. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  64292. this._transparencyShadow = transparent;
  64293. return this;
  64294. };
  64295. /**
  64296. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  64297. * @returns The render target texture if present otherwise, null
  64298. */
  64299. ShadowGenerator.prototype.getShadowMap = function () {
  64300. return this._shadowMap;
  64301. };
  64302. /**
  64303. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  64304. * @returns The render target texture if the shadow map is present otherwise, null
  64305. */
  64306. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  64307. if (this._shadowMap2) {
  64308. return this._shadowMap2;
  64309. }
  64310. return this._shadowMap;
  64311. };
  64312. /**
  64313. * Helper function to add a mesh and its descendants to the list of shadow casters.
  64314. * @param mesh Mesh to add
  64315. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  64316. * @returns the Shadow Generator itself
  64317. */
  64318. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  64319. if (includeDescendants === void 0) { includeDescendants = true; }
  64320. if (!this._shadowMap) {
  64321. return this;
  64322. }
  64323. if (!this._shadowMap.renderList) {
  64324. this._shadowMap.renderList = [];
  64325. }
  64326. this._shadowMap.renderList.push(mesh);
  64327. if (includeDescendants) {
  64328. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  64329. }
  64330. return this;
  64331. var _a;
  64332. };
  64333. /**
  64334. * Helper function to remove a mesh and its descendants from the list of shadow casters
  64335. * @param mesh Mesh to remove
  64336. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  64337. * @returns the Shadow Generator itself
  64338. */
  64339. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  64340. if (includeDescendants === void 0) { includeDescendants = true; }
  64341. if (!this._shadowMap || !this._shadowMap.renderList) {
  64342. return this;
  64343. }
  64344. var index = this._shadowMap.renderList.indexOf(mesh);
  64345. if (index !== -1) {
  64346. this._shadowMap.renderList.splice(index, 1);
  64347. }
  64348. if (includeDescendants) {
  64349. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  64350. var child = _a[_i];
  64351. this.removeShadowCaster(child);
  64352. }
  64353. }
  64354. return this;
  64355. };
  64356. /**
  64357. * Returns the associated light object.
  64358. * @returns the light generating the shadow
  64359. */
  64360. ShadowGenerator.prototype.getLight = function () {
  64361. return this._light;
  64362. };
  64363. ShadowGenerator.prototype._initializeGenerator = function () {
  64364. this._light._markMeshesAsLightDirty();
  64365. this._initializeShadowMap();
  64366. };
  64367. ShadowGenerator.prototype._initializeShadowMap = function () {
  64368. var _this = this;
  64369. // Render target
  64370. var engine = this._scene.getEngine();
  64371. if (engine.webGLVersion > 1) {
  64372. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  64373. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  64374. }
  64375. else {
  64376. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  64377. }
  64378. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64379. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64380. this._shadowMap.anisotropicFilteringLevel = 1;
  64381. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64382. this._shadowMap.renderParticles = false;
  64383. this._shadowMap.ignoreCameraViewport = true;
  64384. // Record Face Index before render.
  64385. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  64386. _this._currentFaceIndex = faceIndex;
  64387. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64388. engine.setColorWrite(false);
  64389. }
  64390. });
  64391. // Custom render function.
  64392. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  64393. // Blur if required afer render.
  64394. this._shadowMap.onAfterUnbindObservable.add(function () {
  64395. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64396. engine.setColorWrite(true);
  64397. }
  64398. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  64399. return;
  64400. }
  64401. var shadowMap = _this.getShadowMapForRendering();
  64402. if (shadowMap) {
  64403. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  64404. }
  64405. });
  64406. // Clear according to the chosen filter.
  64407. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  64408. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64409. this._shadowMap.onClearObservable.add(function (engine) {
  64410. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64411. engine.clear(clearOne, false, true, false);
  64412. }
  64413. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  64414. engine.clear(clearZero, true, true, false);
  64415. }
  64416. else {
  64417. engine.clear(clearOne, true, true, false);
  64418. }
  64419. });
  64420. };
  64421. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  64422. var _this = this;
  64423. var engine = this._scene.getEngine();
  64424. var targetSize = this._mapSize / this.blurScale;
  64425. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  64426. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  64427. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64428. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64429. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64430. }
  64431. if (this.useKernelBlur) {
  64432. 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);
  64433. this._kernelBlurXPostprocess.width = targetSize;
  64434. this._kernelBlurXPostprocess.height = targetSize;
  64435. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  64436. effect.setTexture("textureSampler", _this._shadowMap);
  64437. });
  64438. 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);
  64439. this._kernelBlurXPostprocess.autoClear = false;
  64440. this._kernelBlurYPostprocess.autoClear = false;
  64441. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64442. this._kernelBlurXPostprocess.packedFloat = true;
  64443. this._kernelBlurYPostprocess.packedFloat = true;
  64444. }
  64445. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  64446. }
  64447. else {
  64448. 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);
  64449. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  64450. effect.setFloat2("screenSize", targetSize, targetSize);
  64451. effect.setTexture("textureSampler", _this._shadowMap);
  64452. });
  64453. this._boxBlurPostprocess.autoClear = false;
  64454. this._blurPostProcesses = [this._boxBlurPostprocess];
  64455. }
  64456. };
  64457. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64458. var index;
  64459. var engine = this._scene.getEngine();
  64460. if (depthOnlySubMeshes.length) {
  64461. engine.setColorWrite(false);
  64462. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64463. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  64464. }
  64465. engine.setColorWrite(true);
  64466. }
  64467. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64468. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  64469. }
  64470. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64471. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  64472. }
  64473. if (this._transparencyShadow) {
  64474. for (index = 0; index < transparentSubMeshes.length; index++) {
  64475. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  64476. }
  64477. }
  64478. };
  64479. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  64480. var _this = this;
  64481. var mesh = subMesh.getRenderingMesh();
  64482. var scene = this._scene;
  64483. var engine = scene.getEngine();
  64484. var material = subMesh.getMaterial();
  64485. if (!material) {
  64486. return;
  64487. }
  64488. // Culling
  64489. engine.setState(material.backFaceCulling);
  64490. // Managing instances
  64491. var batch = mesh._getInstancesRenderList(subMesh._id);
  64492. if (batch.mustReturn) {
  64493. return;
  64494. }
  64495. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  64496. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  64497. engine.enableEffect(this._effect);
  64498. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  64499. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  64500. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  64501. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64502. this._effect.setVector3("lightData", this._cachedDirection);
  64503. }
  64504. else {
  64505. this._effect.setVector3("lightData", this._cachedPosition);
  64506. }
  64507. if (scene.activeCamera) {
  64508. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  64509. }
  64510. // Alpha test
  64511. if (material && material.needAlphaTesting()) {
  64512. var alphaTexture = material.getAlphaTestTexture();
  64513. if (alphaTexture) {
  64514. this._effect.setTexture("diffuseSampler", alphaTexture);
  64515. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  64516. }
  64517. }
  64518. // Bones
  64519. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64520. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  64521. }
  64522. // Morph targets
  64523. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  64524. if (this.forceBackFacesOnly) {
  64525. engine.setState(true, 0, false, true);
  64526. }
  64527. // Draw
  64528. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64529. if (this.forceBackFacesOnly) {
  64530. engine.setState(true, 0, false, false);
  64531. }
  64532. }
  64533. else {
  64534. // Need to reset refresh rate of the shadowMap
  64535. if (this._shadowMap) {
  64536. this._shadowMap.resetRefreshCounter();
  64537. }
  64538. }
  64539. };
  64540. ShadowGenerator.prototype._applyFilterValues = function () {
  64541. if (!this._shadowMap) {
  64542. return;
  64543. }
  64544. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  64545. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64546. }
  64547. else {
  64548. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64549. }
  64550. };
  64551. /**
  64552. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64553. * @param onCompiled Callback triggered at the and of the effects compilation
  64554. * @param options Sets of optional options forcing the compilation with different modes
  64555. */
  64556. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  64557. var _this = this;
  64558. var localOptions = __assign({ useInstances: false }, options);
  64559. var shadowMap = this.getShadowMap();
  64560. if (!shadowMap) {
  64561. if (onCompiled) {
  64562. onCompiled(this);
  64563. }
  64564. return;
  64565. }
  64566. var renderList = shadowMap.renderList;
  64567. if (!renderList) {
  64568. if (onCompiled) {
  64569. onCompiled(this);
  64570. }
  64571. return;
  64572. }
  64573. var subMeshes = new Array();
  64574. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  64575. var mesh = renderList_1[_i];
  64576. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  64577. }
  64578. if (subMeshes.length === 0) {
  64579. if (onCompiled) {
  64580. onCompiled(this);
  64581. }
  64582. return;
  64583. }
  64584. var currentIndex = 0;
  64585. var checkReady = function () {
  64586. if (!_this._scene || !_this._scene.getEngine()) {
  64587. return;
  64588. }
  64589. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  64590. currentIndex++;
  64591. if (currentIndex >= subMeshes.length) {
  64592. if (onCompiled) {
  64593. onCompiled(_this);
  64594. }
  64595. return;
  64596. }
  64597. }
  64598. setTimeout(checkReady, 16);
  64599. };
  64600. checkReady();
  64601. };
  64602. /**
  64603. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64604. * @param options Sets of optional options forcing the compilation with different modes
  64605. * @returns A promise that resolves when the compilation completes
  64606. */
  64607. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  64608. var _this = this;
  64609. return new Promise(function (resolve) {
  64610. _this.forceCompilation(function () {
  64611. resolve();
  64612. }, options);
  64613. });
  64614. };
  64615. /**
  64616. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  64617. * @param subMesh The submesh we want to render in the shadow map
  64618. * @param useInstances Defines wether will draw in the map using instances
  64619. * @returns true if ready otherwise, false
  64620. */
  64621. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  64622. var defines = [];
  64623. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64624. defines.push("#define FLOAT");
  64625. }
  64626. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64627. defines.push("#define ESM");
  64628. }
  64629. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  64630. defines.push("#define DEPTHTEXTURE");
  64631. }
  64632. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64633. var mesh = subMesh.getMesh();
  64634. var material = subMesh.getMaterial();
  64635. // Normal bias.
  64636. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  64637. attribs.push(BABYLON.VertexBuffer.NormalKind);
  64638. defines.push("#define NORMAL");
  64639. if (mesh.nonUniformScaling) {
  64640. defines.push("#define NONUNIFORMSCALING");
  64641. }
  64642. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64643. defines.push("#define DIRECTIONINLIGHTDATA");
  64644. }
  64645. }
  64646. // Alpha test
  64647. if (material && material.needAlphaTesting()) {
  64648. var alphaTexture = material.getAlphaTestTexture();
  64649. if (alphaTexture) {
  64650. defines.push("#define ALPHATEST");
  64651. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64652. attribs.push(BABYLON.VertexBuffer.UVKind);
  64653. defines.push("#define UV1");
  64654. }
  64655. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64656. if (alphaTexture.coordinatesIndex === 1) {
  64657. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64658. defines.push("#define UV2");
  64659. }
  64660. }
  64661. }
  64662. }
  64663. // Bones
  64664. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64665. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64666. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64667. if (mesh.numBoneInfluencers > 4) {
  64668. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64669. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64670. }
  64671. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64672. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  64673. }
  64674. else {
  64675. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64676. }
  64677. // Morph targets
  64678. var manager = mesh.morphTargetManager;
  64679. var morphInfluencers = 0;
  64680. if (manager) {
  64681. if (manager.numInfluencers > 0) {
  64682. defines.push("#define MORPHTARGETS");
  64683. morphInfluencers = manager.numInfluencers;
  64684. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  64685. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  64686. }
  64687. }
  64688. // Instances
  64689. if (useInstances) {
  64690. defines.push("#define INSTANCES");
  64691. attribs.push("world0");
  64692. attribs.push("world1");
  64693. attribs.push("world2");
  64694. attribs.push("world3");
  64695. }
  64696. // Get correct effect
  64697. var join = defines.join("\n");
  64698. if (this._cachedDefines !== join) {
  64699. this._cachedDefines = join;
  64700. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  64701. }
  64702. if (!this._effect.isReady()) {
  64703. return false;
  64704. }
  64705. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  64706. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  64707. this._initializeBlurRTTAndPostProcesses();
  64708. }
  64709. }
  64710. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  64711. return false;
  64712. }
  64713. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  64714. return false;
  64715. }
  64716. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  64717. return false;
  64718. }
  64719. return true;
  64720. };
  64721. /**
  64722. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  64723. * @param defines Defines of the material we want to update
  64724. * @param lightIndex Index of the light in the enabled light list of the material
  64725. */
  64726. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  64727. var scene = this._scene;
  64728. var light = this._light;
  64729. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  64730. return;
  64731. }
  64732. defines["SHADOW" + lightIndex] = true;
  64733. if (this.useContactHardeningShadow) {
  64734. defines["SHADOWPCSS" + lightIndex] = true;
  64735. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  64736. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  64737. }
  64738. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  64739. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  64740. }
  64741. // else default to high.
  64742. }
  64743. if (this.usePercentageCloserFiltering) {
  64744. defines["SHADOWPCF" + lightIndex] = true;
  64745. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  64746. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  64747. }
  64748. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  64749. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  64750. }
  64751. // else default to high.
  64752. }
  64753. else if (this.usePoissonSampling) {
  64754. defines["SHADOWPOISSON" + lightIndex] = true;
  64755. }
  64756. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64757. defines["SHADOWESM" + lightIndex] = true;
  64758. }
  64759. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  64760. defines["SHADOWCLOSEESM" + lightIndex] = true;
  64761. }
  64762. if (light.needCube()) {
  64763. defines["SHADOWCUBE" + lightIndex] = true;
  64764. }
  64765. };
  64766. /**
  64767. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  64768. * defined in the generator but impacting the effect).
  64769. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  64770. * @param effect The effect we are binfing the information for
  64771. */
  64772. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  64773. var light = this._light;
  64774. var scene = this._scene;
  64775. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  64776. return;
  64777. }
  64778. var camera = scene.activeCamera;
  64779. if (!camera) {
  64780. return;
  64781. }
  64782. var shadowMap = this.getShadowMap();
  64783. if (!shadowMap) {
  64784. return;
  64785. }
  64786. if (!light.needCube()) {
  64787. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  64788. }
  64789. // Only PCF uses depth stencil texture.
  64790. if (this._filter === ShadowGenerator.FILTER_PCF) {
  64791. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64792. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  64793. }
  64794. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  64795. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64796. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  64797. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  64798. }
  64799. else {
  64800. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64801. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  64802. }
  64803. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  64804. };
  64805. /**
  64806. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  64807. * (eq to shadow prjection matrix * light transform matrix)
  64808. * @returns The transform matrix used to create the shadow map
  64809. */
  64810. ShadowGenerator.prototype.getTransformMatrix = function () {
  64811. var scene = this._scene;
  64812. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  64813. return this._transformMatrix;
  64814. }
  64815. this._currentRenderID = scene.getRenderId();
  64816. this._currentFaceIndexCache = this._currentFaceIndex;
  64817. var lightPosition = this._light.position;
  64818. if (this._light.computeTransformedInformation()) {
  64819. lightPosition = this._light.transformedPosition;
  64820. }
  64821. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  64822. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  64823. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  64824. }
  64825. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  64826. this._cachedPosition.copyFrom(lightPosition);
  64827. this._cachedDirection.copyFrom(this._lightDirection);
  64828. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  64829. var shadowMap = this.getShadowMap();
  64830. if (shadowMap) {
  64831. var renderList = shadowMap.renderList;
  64832. if (renderList) {
  64833. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  64834. }
  64835. }
  64836. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  64837. }
  64838. return this._transformMatrix;
  64839. };
  64840. /**
  64841. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  64842. * Cube and 2D textures for instance.
  64843. */
  64844. ShadowGenerator.prototype.recreateShadowMap = function () {
  64845. var shadowMap = this._shadowMap;
  64846. if (!shadowMap) {
  64847. return;
  64848. }
  64849. // Track render list.
  64850. var renderList = shadowMap.renderList;
  64851. // Clean up existing data.
  64852. this._disposeRTTandPostProcesses();
  64853. // Reinitializes.
  64854. this._initializeGenerator();
  64855. // Reaffect the filter to ensure a correct fallback if necessary.
  64856. this.filter = this.filter;
  64857. // Reaffect the filter.
  64858. this._applyFilterValues();
  64859. // Reaffect Render List.
  64860. this._shadowMap.renderList = renderList;
  64861. };
  64862. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  64863. if (this._shadowMap2) {
  64864. this._shadowMap2.dispose();
  64865. this._shadowMap2 = null;
  64866. }
  64867. if (this._boxBlurPostprocess) {
  64868. this._boxBlurPostprocess.dispose();
  64869. this._boxBlurPostprocess = null;
  64870. }
  64871. if (this._kernelBlurXPostprocess) {
  64872. this._kernelBlurXPostprocess.dispose();
  64873. this._kernelBlurXPostprocess = null;
  64874. }
  64875. if (this._kernelBlurYPostprocess) {
  64876. this._kernelBlurYPostprocess.dispose();
  64877. this._kernelBlurYPostprocess = null;
  64878. }
  64879. this._blurPostProcesses = [];
  64880. };
  64881. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  64882. if (this._shadowMap) {
  64883. this._shadowMap.dispose();
  64884. this._shadowMap = null;
  64885. }
  64886. this._disposeBlurPostProcesses();
  64887. };
  64888. /**
  64889. * Disposes the ShadowGenerator.
  64890. * Returns nothing.
  64891. */
  64892. ShadowGenerator.prototype.dispose = function () {
  64893. this._disposeRTTandPostProcesses();
  64894. if (this._light) {
  64895. this._light._shadowGenerator = null;
  64896. this._light._markMeshesAsLightDirty();
  64897. }
  64898. };
  64899. /**
  64900. * Serializes the shadow generator setup to a json object.
  64901. * @returns The serialized JSON object
  64902. */
  64903. ShadowGenerator.prototype.serialize = function () {
  64904. var serializationObject = {};
  64905. var shadowMap = this.getShadowMap();
  64906. if (!shadowMap) {
  64907. return serializationObject;
  64908. }
  64909. serializationObject.lightId = this._light.id;
  64910. serializationObject.mapSize = shadowMap.getRenderSize();
  64911. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  64912. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  64913. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  64914. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  64915. serializationObject.usePoissonSampling = this.usePoissonSampling;
  64916. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  64917. serializationObject.depthScale = this.depthScale;
  64918. serializationObject.darkness = this.getDarkness();
  64919. serializationObject.blurBoxOffset = this.blurBoxOffset;
  64920. serializationObject.blurKernel = this.blurKernel;
  64921. serializationObject.blurScale = this.blurScale;
  64922. serializationObject.useKernelBlur = this.useKernelBlur;
  64923. serializationObject.transparencyShadow = this._transparencyShadow;
  64924. serializationObject.bias = this.bias;
  64925. serializationObject.normalBias = this.normalBias;
  64926. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  64927. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  64928. serializationObject.filteringQuality = this.filteringQuality;
  64929. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  64930. serializationObject.renderList = [];
  64931. if (shadowMap.renderList) {
  64932. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  64933. var mesh = shadowMap.renderList[meshIndex];
  64934. serializationObject.renderList.push(mesh.id);
  64935. }
  64936. }
  64937. return serializationObject;
  64938. };
  64939. /**
  64940. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  64941. * @param parsedShadowGenerator The JSON object to parse
  64942. * @param scene The scene to create the shadow map for
  64943. * @returns The parsed shadow generator
  64944. */
  64945. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  64946. //casting to point light, as light is missing the position attr and typescript complains.
  64947. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  64948. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  64949. var shadowMap = shadowGenerator.getShadowMap();
  64950. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  64951. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  64952. meshes.forEach(function (mesh) {
  64953. if (!shadowMap) {
  64954. return;
  64955. }
  64956. if (!shadowMap.renderList) {
  64957. shadowMap.renderList = [];
  64958. }
  64959. shadowMap.renderList.push(mesh);
  64960. });
  64961. }
  64962. if (parsedShadowGenerator.usePoissonSampling) {
  64963. shadowGenerator.usePoissonSampling = true;
  64964. }
  64965. else if (parsedShadowGenerator.useExponentialShadowMap) {
  64966. shadowGenerator.useExponentialShadowMap = true;
  64967. }
  64968. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  64969. shadowGenerator.useBlurExponentialShadowMap = true;
  64970. }
  64971. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  64972. shadowGenerator.useCloseExponentialShadowMap = true;
  64973. }
  64974. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  64975. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  64976. }
  64977. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  64978. shadowGenerator.usePercentageCloserFiltering = true;
  64979. }
  64980. else if (parsedShadowGenerator.useContactHardeningShadow) {
  64981. shadowGenerator.useContactHardeningShadow = true;
  64982. }
  64983. if (parsedShadowGenerator.filteringQuality) {
  64984. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  64985. }
  64986. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  64987. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  64988. }
  64989. else if (parsedShadowGenerator.useVarianceShadowMap) {
  64990. shadowGenerator.useExponentialShadowMap = true;
  64991. }
  64992. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  64993. shadowGenerator.useBlurExponentialShadowMap = true;
  64994. }
  64995. if (parsedShadowGenerator.depthScale) {
  64996. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  64997. }
  64998. if (parsedShadowGenerator.blurScale) {
  64999. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  65000. }
  65001. if (parsedShadowGenerator.blurBoxOffset) {
  65002. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  65003. }
  65004. if (parsedShadowGenerator.useKernelBlur) {
  65005. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  65006. }
  65007. if (parsedShadowGenerator.blurKernel) {
  65008. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  65009. }
  65010. if (parsedShadowGenerator.bias !== undefined) {
  65011. shadowGenerator.bias = parsedShadowGenerator.bias;
  65012. }
  65013. if (parsedShadowGenerator.normalBias !== undefined) {
  65014. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  65015. }
  65016. if (parsedShadowGenerator.darkness) {
  65017. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  65018. }
  65019. if (parsedShadowGenerator.transparencyShadow) {
  65020. shadowGenerator.setTransparencyShadow(true);
  65021. }
  65022. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  65023. return shadowGenerator;
  65024. };
  65025. /**
  65026. * Shadow generator mode None: no filtering applied.
  65027. */
  65028. ShadowGenerator.FILTER_NONE = 0;
  65029. /**
  65030. * Shadow generator mode ESM: Exponential Shadow Mapping.
  65031. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65032. */
  65033. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  65034. /**
  65035. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  65036. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  65037. */
  65038. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  65039. /**
  65040. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  65041. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65042. */
  65043. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  65044. /**
  65045. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  65046. * edge artifacts on steep falloff.
  65047. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65048. */
  65049. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  65050. /**
  65051. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  65052. * edge artifacts on steep falloff.
  65053. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65054. */
  65055. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  65056. /**
  65057. * Shadow generator mode PCF: Percentage Closer Filtering
  65058. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65059. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  65060. */
  65061. ShadowGenerator.FILTER_PCF = 6;
  65062. /**
  65063. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  65064. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65065. * Contact Hardening
  65066. */
  65067. ShadowGenerator.FILTER_PCSS = 7;
  65068. /**
  65069. * Reserved for PCF and PCSS
  65070. * Highest Quality.
  65071. *
  65072. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  65073. *
  65074. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  65075. */
  65076. ShadowGenerator.QUALITY_HIGH = 0;
  65077. /**
  65078. * Reserved for PCF and PCSS
  65079. * Good tradeoff for quality/perf cross devices
  65080. *
  65081. * Execute PCF on a 3*3 kernel.
  65082. *
  65083. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  65084. */
  65085. ShadowGenerator.QUALITY_MEDIUM = 1;
  65086. /**
  65087. * Reserved for PCF and PCSS
  65088. * The lowest quality but the fastest.
  65089. *
  65090. * Execute PCF on a 1*1 kernel.
  65091. *
  65092. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  65093. */
  65094. ShadowGenerator.QUALITY_LOW = 2;
  65095. return ShadowGenerator;
  65096. }());
  65097. BABYLON.ShadowGenerator = ShadowGenerator;
  65098. })(BABYLON || (BABYLON = {}));
  65099. //# sourceMappingURL=babylon.shadowGenerator.js.map
  65100. "use strict";
  65101. var BABYLON;
  65102. (function (BABYLON) {
  65103. var DefaultLoadingScreen = /** @class */ (function () {
  65104. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  65105. if (_loadingText === void 0) { _loadingText = ""; }
  65106. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  65107. var _this = this;
  65108. this._renderingCanvas = _renderingCanvas;
  65109. this._loadingText = _loadingText;
  65110. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  65111. // Resize
  65112. this._resizeLoadingUI = function () {
  65113. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  65114. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  65115. if (!_this._loadingDiv) {
  65116. return;
  65117. }
  65118. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  65119. _this._loadingDiv.style.left = canvasRect.left + "px";
  65120. _this._loadingDiv.style.top = canvasRect.top + "px";
  65121. _this._loadingDiv.style.width = canvasRect.width + "px";
  65122. _this._loadingDiv.style.height = canvasRect.height + "px";
  65123. };
  65124. }
  65125. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  65126. if (this._loadingDiv) {
  65127. // Do not add a loading screen if there is already one
  65128. return;
  65129. }
  65130. this._loadingDiv = document.createElement("div");
  65131. this._loadingDiv.id = "babylonjsLoadingDiv";
  65132. this._loadingDiv.style.opacity = "0";
  65133. this._loadingDiv.style.transition = "opacity 1.5s ease";
  65134. this._loadingDiv.style.pointerEvents = "none";
  65135. // Loading text
  65136. this._loadingTextDiv = document.createElement("div");
  65137. this._loadingTextDiv.style.position = "absolute";
  65138. this._loadingTextDiv.style.left = "0";
  65139. this._loadingTextDiv.style.top = "50%";
  65140. this._loadingTextDiv.style.marginTop = "80px";
  65141. this._loadingTextDiv.style.width = "100%";
  65142. this._loadingTextDiv.style.height = "20px";
  65143. this._loadingTextDiv.style.fontFamily = "Arial";
  65144. this._loadingTextDiv.style.fontSize = "14px";
  65145. this._loadingTextDiv.style.color = "white";
  65146. this._loadingTextDiv.style.textAlign = "center";
  65147. this._loadingTextDiv.innerHTML = "Loading";
  65148. this._loadingDiv.appendChild(this._loadingTextDiv);
  65149. //set the predefined text
  65150. this._loadingTextDiv.innerHTML = this._loadingText;
  65151. // Generating keyframes
  65152. var style = document.createElement('style');
  65153. style.type = 'text/css';
  65154. 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 }";
  65155. style.innerHTML = keyFrames;
  65156. document.getElementsByTagName('head')[0].appendChild(style);
  65157. // Loading img
  65158. var imgBack = new Image();
  65159. 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";
  65160. imgBack.style.position = "absolute";
  65161. imgBack.style.left = "50%";
  65162. imgBack.style.top = "50%";
  65163. imgBack.style.marginLeft = "-60px";
  65164. imgBack.style.marginTop = "-60px";
  65165. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  65166. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  65167. imgBack.style.transformOrigin = "50% 50%";
  65168. imgBack.style.webkitTransformOrigin = "50% 50%";
  65169. this._loadingDiv.appendChild(imgBack);
  65170. this._resizeLoadingUI();
  65171. window.addEventListener("resize", this._resizeLoadingUI);
  65172. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  65173. document.body.appendChild(this._loadingDiv);
  65174. this._loadingDiv.style.opacity = "1";
  65175. };
  65176. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  65177. var _this = this;
  65178. if (!this._loadingDiv) {
  65179. return;
  65180. }
  65181. var onTransitionEnd = function () {
  65182. if (!_this._loadingDiv) {
  65183. return;
  65184. }
  65185. document.body.removeChild(_this._loadingDiv);
  65186. window.removeEventListener("resize", _this._resizeLoadingUI);
  65187. _this._loadingDiv = null;
  65188. };
  65189. this._loadingDiv.style.opacity = "0";
  65190. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  65191. };
  65192. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  65193. set: function (text) {
  65194. this._loadingText = text;
  65195. if (this._loadingTextDiv) {
  65196. this._loadingTextDiv.innerHTML = this._loadingText;
  65197. }
  65198. },
  65199. enumerable: true,
  65200. configurable: true
  65201. });
  65202. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  65203. get: function () {
  65204. return this._loadingDivBackgroundColor;
  65205. },
  65206. set: function (color) {
  65207. this._loadingDivBackgroundColor = color;
  65208. if (!this._loadingDiv) {
  65209. return;
  65210. }
  65211. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  65212. },
  65213. enumerable: true,
  65214. configurable: true
  65215. });
  65216. return DefaultLoadingScreen;
  65217. }());
  65218. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  65219. })(BABYLON || (BABYLON = {}));
  65220. //# sourceMappingURL=babylon.loadingScreen.js.map
  65221. "use strict";
  65222. var BABYLON;
  65223. (function (BABYLON) {
  65224. var SceneLoaderProgressEvent = /** @class */ (function () {
  65225. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  65226. this.lengthComputable = lengthComputable;
  65227. this.loaded = loaded;
  65228. this.total = total;
  65229. }
  65230. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  65231. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  65232. };
  65233. return SceneLoaderProgressEvent;
  65234. }());
  65235. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  65236. var SceneLoader = /** @class */ (function () {
  65237. function SceneLoader() {
  65238. }
  65239. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  65240. get: function () {
  65241. return 0;
  65242. },
  65243. enumerable: true,
  65244. configurable: true
  65245. });
  65246. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  65247. get: function () {
  65248. return 1;
  65249. },
  65250. enumerable: true,
  65251. configurable: true
  65252. });
  65253. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  65254. get: function () {
  65255. return 2;
  65256. },
  65257. enumerable: true,
  65258. configurable: true
  65259. });
  65260. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  65261. get: function () {
  65262. return 3;
  65263. },
  65264. enumerable: true,
  65265. configurable: true
  65266. });
  65267. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  65268. get: function () {
  65269. return SceneLoader._ForceFullSceneLoadingForIncremental;
  65270. },
  65271. set: function (value) {
  65272. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  65273. },
  65274. enumerable: true,
  65275. configurable: true
  65276. });
  65277. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  65278. get: function () {
  65279. return SceneLoader._ShowLoadingScreen;
  65280. },
  65281. set: function (value) {
  65282. SceneLoader._ShowLoadingScreen = value;
  65283. },
  65284. enumerable: true,
  65285. configurable: true
  65286. });
  65287. Object.defineProperty(SceneLoader, "loggingLevel", {
  65288. get: function () {
  65289. return SceneLoader._loggingLevel;
  65290. },
  65291. set: function (value) {
  65292. SceneLoader._loggingLevel = value;
  65293. },
  65294. enumerable: true,
  65295. configurable: true
  65296. });
  65297. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  65298. get: function () {
  65299. return SceneLoader._CleanBoneMatrixWeights;
  65300. },
  65301. set: function (value) {
  65302. SceneLoader._CleanBoneMatrixWeights = value;
  65303. },
  65304. enumerable: true,
  65305. configurable: true
  65306. });
  65307. SceneLoader._getDefaultPlugin = function () {
  65308. return SceneLoader._registeredPlugins[".babylon"];
  65309. };
  65310. SceneLoader._getPluginForExtension = function (extension) {
  65311. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  65312. if (registeredPlugin) {
  65313. return registeredPlugin;
  65314. }
  65315. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  65316. return SceneLoader._getDefaultPlugin();
  65317. };
  65318. SceneLoader._getPluginForDirectLoad = function (data) {
  65319. for (var extension in SceneLoader._registeredPlugins) {
  65320. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  65321. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  65322. return SceneLoader._registeredPlugins[extension];
  65323. }
  65324. }
  65325. return SceneLoader._getDefaultPlugin();
  65326. };
  65327. SceneLoader._getPluginForFilename = function (sceneFilename) {
  65328. if (sceneFilename.name) {
  65329. sceneFilename = sceneFilename.name;
  65330. }
  65331. var queryStringPosition = sceneFilename.indexOf("?");
  65332. if (queryStringPosition !== -1) {
  65333. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  65334. }
  65335. var dotPosition = sceneFilename.lastIndexOf(".");
  65336. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  65337. return SceneLoader._getPluginForExtension(extension);
  65338. };
  65339. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  65340. SceneLoader._getDirectLoad = function (sceneFilename) {
  65341. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  65342. return sceneFilename.substr(5);
  65343. }
  65344. return null;
  65345. };
  65346. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  65347. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  65348. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  65349. var plugin;
  65350. if (registeredPlugin.plugin.createPlugin) {
  65351. plugin = registeredPlugin.plugin.createPlugin();
  65352. }
  65353. else {
  65354. plugin = registeredPlugin.plugin;
  65355. }
  65356. var useArrayBuffer = registeredPlugin.isBinary;
  65357. var database;
  65358. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  65359. var dataCallback = function (data, responseURL) {
  65360. if (scene.isDisposed) {
  65361. onError("Scene has been disposed");
  65362. return;
  65363. }
  65364. scene.database = database;
  65365. onSuccess(plugin, data, responseURL);
  65366. };
  65367. var request = null;
  65368. var pluginDisposed = false;
  65369. var onDisposeObservable = plugin.onDisposeObservable;
  65370. if (onDisposeObservable) {
  65371. onDisposeObservable.add(function () {
  65372. pluginDisposed = true;
  65373. if (request) {
  65374. request.abort();
  65375. request = null;
  65376. }
  65377. onDispose();
  65378. });
  65379. }
  65380. var manifestChecked = function () {
  65381. if (pluginDisposed) {
  65382. return;
  65383. }
  65384. var url = rootUrl + sceneFilename;
  65385. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  65386. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  65387. } : undefined, database, useArrayBuffer, function (request, exception) {
  65388. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  65389. });
  65390. };
  65391. if (directLoad) {
  65392. dataCallback(directLoad);
  65393. return plugin;
  65394. }
  65395. if (rootUrl.indexOf("file:") === -1) {
  65396. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  65397. if (canUseOfflineSupport) {
  65398. // Also check for exceptions
  65399. var exceptionFound = false;
  65400. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  65401. var regex = _a[_i];
  65402. if (regex.test(rootUrl + sceneFilename)) {
  65403. exceptionFound = true;
  65404. break;
  65405. }
  65406. }
  65407. canUseOfflineSupport = !exceptionFound;
  65408. }
  65409. if (canUseOfflineSupport) {
  65410. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  65411. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  65412. }
  65413. else {
  65414. manifestChecked();
  65415. }
  65416. }
  65417. else {
  65418. var fileOrString = sceneFilename;
  65419. if (fileOrString.name) {
  65420. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  65421. }
  65422. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  65423. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  65424. }
  65425. else {
  65426. onError("Unable to find file named " + sceneFilename);
  65427. }
  65428. }
  65429. return plugin;
  65430. };
  65431. // Public functions
  65432. SceneLoader.GetPluginForExtension = function (extension) {
  65433. return SceneLoader._getPluginForExtension(extension).plugin;
  65434. };
  65435. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  65436. return !!SceneLoader._registeredPlugins[extension];
  65437. };
  65438. SceneLoader.RegisterPlugin = function (plugin) {
  65439. if (typeof plugin.extensions === "string") {
  65440. var extension = plugin.extensions;
  65441. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65442. plugin: plugin,
  65443. isBinary: false
  65444. };
  65445. }
  65446. else {
  65447. var extensions = plugin.extensions;
  65448. Object.keys(extensions).forEach(function (extension) {
  65449. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65450. plugin: plugin,
  65451. isBinary: extensions[extension].isBinary
  65452. };
  65453. });
  65454. }
  65455. };
  65456. /**
  65457. * Import meshes into a scene
  65458. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65459. * @param rootUrl a string that defines the root url for scene and resources
  65460. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65461. * @param scene the instance of BABYLON.Scene to append to
  65462. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  65463. * @param onProgress a callback with a progress event for each file being loaded
  65464. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65465. * @param pluginExtension the extension used to determine the plugin
  65466. * @returns The loaded plugin
  65467. */
  65468. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65469. if (onSuccess === void 0) { onSuccess = null; }
  65470. if (onProgress === void 0) { onProgress = null; }
  65471. if (onError === void 0) { onError = null; }
  65472. if (pluginExtension === void 0) { pluginExtension = null; }
  65473. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65474. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65475. return null;
  65476. }
  65477. var loadingToken = {};
  65478. scene._addPendingData(loadingToken);
  65479. var disposeHandler = function () {
  65480. scene._removePendingData(loadingToken);
  65481. };
  65482. var errorHandler = function (message, exception) {
  65483. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  65484. if (onError) {
  65485. onError(scene, errorMessage, exception);
  65486. }
  65487. else {
  65488. BABYLON.Tools.Error(errorMessage);
  65489. // should the exception be thrown?
  65490. }
  65491. disposeHandler();
  65492. };
  65493. var progressHandler = onProgress ? function (event) {
  65494. try {
  65495. onProgress(event);
  65496. }
  65497. catch (e) {
  65498. errorHandler("Error in onProgress callback", e);
  65499. }
  65500. } : undefined;
  65501. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  65502. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  65503. if (onSuccess) {
  65504. try {
  65505. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  65506. }
  65507. catch (e) {
  65508. errorHandler("Error in onSuccess callback", e);
  65509. }
  65510. }
  65511. scene._removePendingData(loadingToken);
  65512. };
  65513. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65514. if (plugin.rewriteRootURL) {
  65515. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  65516. }
  65517. if (sceneFilename === "") {
  65518. if (sceneFilename === "") {
  65519. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65520. }
  65521. }
  65522. if (plugin.importMesh) {
  65523. var syncedPlugin = plugin;
  65524. var meshes = new Array();
  65525. var particleSystems = new Array();
  65526. var skeletons = new Array();
  65527. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  65528. return;
  65529. }
  65530. scene.loadingPluginName = plugin.name;
  65531. successHandler(meshes, particleSystems, skeletons, []);
  65532. }
  65533. else {
  65534. var asyncedPlugin = plugin;
  65535. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  65536. scene.loadingPluginName = plugin.name;
  65537. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  65538. }).catch(function (error) {
  65539. errorHandler(error.message, error);
  65540. });
  65541. }
  65542. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65543. };
  65544. /**
  65545. * Import meshes into a scene
  65546. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65547. * @param rootUrl a string that defines the root url for scene and resources
  65548. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65549. * @param scene the instance of BABYLON.Scene to append to
  65550. * @param onProgress a callback with a progress event for each file being loaded
  65551. * @param pluginExtension the extension used to determine the plugin
  65552. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  65553. */
  65554. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65555. if (onProgress === void 0) { onProgress = null; }
  65556. if (pluginExtension === void 0) { pluginExtension = null; }
  65557. return new Promise(function (resolve, reject) {
  65558. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  65559. resolve({
  65560. meshes: meshes,
  65561. particleSystems: particleSystems,
  65562. skeletons: skeletons,
  65563. animationGroups: animationGroups
  65564. });
  65565. }, onProgress, function (scene, message, exception) {
  65566. reject(exception || new Error(message));
  65567. });
  65568. });
  65569. };
  65570. /**
  65571. * Load a scene
  65572. * @param rootUrl a string that defines the root url for scene and resources
  65573. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65574. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65575. * @param onSuccess a callback with the scene when import succeeds
  65576. * @param onProgress a callback with a progress event for each file being loaded
  65577. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65578. * @param pluginExtension the extension used to determine the plugin
  65579. * @returns The loaded plugin
  65580. */
  65581. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  65582. if (onSuccess === void 0) { onSuccess = null; }
  65583. if (onProgress === void 0) { onProgress = null; }
  65584. if (onError === void 0) { onError = null; }
  65585. if (pluginExtension === void 0) { pluginExtension = null; }
  65586. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  65587. };
  65588. /**
  65589. * Load a scene
  65590. * @param rootUrl a string that defines the root url for scene and resources
  65591. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65592. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65593. * @param onProgress a callback with a progress event for each file being loaded
  65594. * @param pluginExtension the extension used to determine the plugin
  65595. * @returns The loaded scene
  65596. */
  65597. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  65598. if (onProgress === void 0) { onProgress = null; }
  65599. if (pluginExtension === void 0) { pluginExtension = null; }
  65600. return new Promise(function (resolve, reject) {
  65601. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  65602. resolve(scene);
  65603. }, onProgress, function (scene, message, exception) {
  65604. reject(exception || new Error(message));
  65605. }, pluginExtension);
  65606. });
  65607. };
  65608. /**
  65609. * Append a scene
  65610. * @param rootUrl a string that defines the root url for scene and resources
  65611. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65612. * @param scene is the instance of BABYLON.Scene to append to
  65613. * @param onSuccess a callback with the scene when import succeeds
  65614. * @param onProgress a callback with a progress event for each file being loaded
  65615. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65616. * @param pluginExtension the extension used to determine the plugin
  65617. * @returns The loaded plugin
  65618. */
  65619. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65620. if (onSuccess === void 0) { onSuccess = null; }
  65621. if (onProgress === void 0) { onProgress = null; }
  65622. if (onError === void 0) { onError = null; }
  65623. if (pluginExtension === void 0) { pluginExtension = null; }
  65624. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65625. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65626. return null;
  65627. }
  65628. if (SceneLoader.ShowLoadingScreen) {
  65629. scene.getEngine().displayLoadingUI();
  65630. }
  65631. var loadingToken = {};
  65632. scene._addPendingData(loadingToken);
  65633. var disposeHandler = function () {
  65634. scene._removePendingData(loadingToken);
  65635. scene.getEngine().hideLoadingUI();
  65636. };
  65637. var errorHandler = function (message, exception) {
  65638. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65639. if (onError) {
  65640. onError(scene, errorMessage, exception);
  65641. }
  65642. else {
  65643. BABYLON.Tools.Error(errorMessage);
  65644. // should the exception be thrown?
  65645. }
  65646. disposeHandler();
  65647. };
  65648. var progressHandler = onProgress ? function (event) {
  65649. try {
  65650. onProgress(event);
  65651. }
  65652. catch (e) {
  65653. errorHandler("Error in onProgress callback", e);
  65654. }
  65655. } : undefined;
  65656. var successHandler = function () {
  65657. if (onSuccess) {
  65658. try {
  65659. onSuccess(scene);
  65660. }
  65661. catch (e) {
  65662. errorHandler("Error in onSuccess callback", e);
  65663. }
  65664. }
  65665. scene._removePendingData(loadingToken);
  65666. };
  65667. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65668. if (sceneFilename === "") {
  65669. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65670. }
  65671. if (plugin.load) {
  65672. var syncedPlugin = plugin;
  65673. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  65674. return;
  65675. }
  65676. scene.loadingPluginName = plugin.name;
  65677. successHandler();
  65678. }
  65679. else {
  65680. var asyncedPlugin = plugin;
  65681. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  65682. scene.loadingPluginName = plugin.name;
  65683. successHandler();
  65684. }).catch(function (error) {
  65685. errorHandler(error.message, error);
  65686. });
  65687. }
  65688. if (SceneLoader.ShowLoadingScreen) {
  65689. scene.executeWhenReady(function () {
  65690. scene.getEngine().hideLoadingUI();
  65691. });
  65692. }
  65693. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65694. };
  65695. /**
  65696. * Append a scene
  65697. * @param rootUrl a string that defines the root url for scene and resources
  65698. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65699. * @param scene is the instance of BABYLON.Scene to append to
  65700. * @param onProgress a callback with a progress event for each file being loaded
  65701. * @param pluginExtension the extension used to determine the plugin
  65702. * @returns The given scene
  65703. */
  65704. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65705. if (onProgress === void 0) { onProgress = null; }
  65706. if (pluginExtension === void 0) { pluginExtension = null; }
  65707. return new Promise(function (resolve, reject) {
  65708. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  65709. resolve(scene);
  65710. }, onProgress, function (scene, message, exception) {
  65711. reject(exception || new Error(message));
  65712. }, pluginExtension);
  65713. });
  65714. };
  65715. /**
  65716. * Load a scene into an asset container
  65717. * @param rootUrl a string that defines the root url for scene and resources
  65718. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65719. * @param scene is the instance of BABYLON.Scene to append to
  65720. * @param onSuccess a callback with the scene when import succeeds
  65721. * @param onProgress a callback with a progress event for each file being loaded
  65722. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65723. * @param pluginExtension the extension used to determine the plugin
  65724. * @returns The loaded plugin
  65725. */
  65726. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65727. if (onSuccess === void 0) { onSuccess = null; }
  65728. if (onProgress === void 0) { onProgress = null; }
  65729. if (onError === void 0) { onError = null; }
  65730. if (pluginExtension === void 0) { pluginExtension = null; }
  65731. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65732. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65733. return null;
  65734. }
  65735. var loadingToken = {};
  65736. scene._addPendingData(loadingToken);
  65737. var disposeHandler = function () {
  65738. scene._removePendingData(loadingToken);
  65739. };
  65740. var errorHandler = function (message, exception) {
  65741. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65742. if (onError) {
  65743. onError(scene, errorMessage, exception);
  65744. }
  65745. else {
  65746. BABYLON.Tools.Error(errorMessage);
  65747. // should the exception be thrown?
  65748. }
  65749. disposeHandler();
  65750. };
  65751. var progressHandler = onProgress ? function (event) {
  65752. try {
  65753. onProgress(event);
  65754. }
  65755. catch (e) {
  65756. errorHandler("Error in onProgress callback", e);
  65757. }
  65758. } : undefined;
  65759. var successHandler = function (assets) {
  65760. if (onSuccess) {
  65761. try {
  65762. onSuccess(assets);
  65763. }
  65764. catch (e) {
  65765. errorHandler("Error in onSuccess callback", e);
  65766. }
  65767. }
  65768. scene._removePendingData(loadingToken);
  65769. };
  65770. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65771. if (plugin.loadAssetContainer) {
  65772. var syncedPlugin = plugin;
  65773. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  65774. if (!assetContainer) {
  65775. return;
  65776. }
  65777. scene.loadingPluginName = plugin.name;
  65778. successHandler(assetContainer);
  65779. }
  65780. else if (plugin.loadAssetContainerAsync) {
  65781. var asyncedPlugin = plugin;
  65782. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  65783. scene.loadingPluginName = plugin.name;
  65784. successHandler(assetContainer);
  65785. }).catch(function (error) {
  65786. errorHandler(error.message, error);
  65787. });
  65788. }
  65789. else {
  65790. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  65791. }
  65792. if (SceneLoader.ShowLoadingScreen) {
  65793. scene.executeWhenReady(function () {
  65794. scene.getEngine().hideLoadingUI();
  65795. });
  65796. }
  65797. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65798. };
  65799. /**
  65800. * Load a scene into an asset container
  65801. * @param rootUrl a string that defines the root url for scene and resources
  65802. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65803. * @param scene is the instance of BABYLON.Scene to append to
  65804. * @param onProgress a callback with a progress event for each file being loaded
  65805. * @param pluginExtension the extension used to determine the plugin
  65806. * @returns The loaded asset container
  65807. */
  65808. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65809. if (onProgress === void 0) { onProgress = null; }
  65810. if (pluginExtension === void 0) { pluginExtension = null; }
  65811. return new Promise(function (resolve, reject) {
  65812. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  65813. resolve(assetContainer);
  65814. }, onProgress, function (scene, message, exception) {
  65815. reject(exception || new Error(message));
  65816. }, pluginExtension);
  65817. });
  65818. };
  65819. // Flags
  65820. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  65821. SceneLoader._ShowLoadingScreen = true;
  65822. SceneLoader._CleanBoneMatrixWeights = false;
  65823. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  65824. // Members
  65825. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  65826. SceneLoader._registeredPlugins = {};
  65827. return SceneLoader;
  65828. }());
  65829. BABYLON.SceneLoader = SceneLoader;
  65830. ;
  65831. })(BABYLON || (BABYLON = {}));
  65832. //# sourceMappingURL=babylon.sceneLoader.js.map
  65833. "use strict";
  65834. var BABYLON;
  65835. (function (BABYLON) {
  65836. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  65837. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  65838. var parsedMaterial = parsedData.materials[index];
  65839. if (parsedMaterial.id === id) {
  65840. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  65841. }
  65842. }
  65843. return null;
  65844. };
  65845. var isDescendantOf = function (mesh, names, hierarchyIds) {
  65846. for (var i in names) {
  65847. if (mesh.name === names[i]) {
  65848. hierarchyIds.push(mesh.id);
  65849. return true;
  65850. }
  65851. }
  65852. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  65853. hierarchyIds.push(mesh.id);
  65854. return true;
  65855. }
  65856. return false;
  65857. };
  65858. var logOperation = function (operation, producer) {
  65859. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  65860. };
  65861. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  65862. if (addToScene === void 0) { addToScene = false; }
  65863. var container = new BABYLON.AssetContainer(scene);
  65864. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  65865. // when SceneLoader.debugLogging = true (default), or exception encountered.
  65866. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  65867. // and avoid problems with multiple concurrent .babylon loads.
  65868. var log = "importScene has failed JSON parse";
  65869. try {
  65870. var parsedData = JSON.parse(data);
  65871. log = "";
  65872. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  65873. var index;
  65874. var cache;
  65875. // Lights
  65876. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  65877. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  65878. var parsedLight = parsedData.lights[index];
  65879. var light = BABYLON.Light.Parse(parsedLight, scene);
  65880. if (light) {
  65881. container.lights.push(light);
  65882. log += (index === 0 ? "\n\tLights:" : "");
  65883. log += "\n\t\t" + light.toString(fullDetails);
  65884. }
  65885. }
  65886. }
  65887. // Animations
  65888. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  65889. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  65890. var parsedAnimation = parsedData.animations[index];
  65891. var animation = BABYLON.Animation.Parse(parsedAnimation);
  65892. scene.animations.push(animation);
  65893. container.animations.push(animation);
  65894. log += (index === 0 ? "\n\tAnimations:" : "");
  65895. log += "\n\t\t" + animation.toString(fullDetails);
  65896. }
  65897. }
  65898. // Materials
  65899. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  65900. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  65901. var parsedMaterial = parsedData.materials[index];
  65902. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  65903. container.materials.push(mat);
  65904. log += (index === 0 ? "\n\tMaterials:" : "");
  65905. log += "\n\t\t" + mat.toString(fullDetails);
  65906. }
  65907. }
  65908. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  65909. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  65910. var parsedMultiMaterial = parsedData.multiMaterials[index];
  65911. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  65912. container.multiMaterials.push(mmat);
  65913. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  65914. log += "\n\t\t" + mmat.toString(fullDetails);
  65915. }
  65916. }
  65917. // Morph targets
  65918. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  65919. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  65920. var managerData = _a[_i];
  65921. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  65922. }
  65923. }
  65924. // Skeletons
  65925. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  65926. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  65927. var parsedSkeleton = parsedData.skeletons[index];
  65928. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  65929. container.skeletons.push(skeleton);
  65930. log += (index === 0 ? "\n\tSkeletons:" : "");
  65931. log += "\n\t\t" + skeleton.toString(fullDetails);
  65932. }
  65933. }
  65934. // Geometries
  65935. var geometries = parsedData.geometries;
  65936. if (geometries !== undefined && geometries !== null) {
  65937. var addedGeometry = new Array();
  65938. // Boxes
  65939. var boxes = geometries.boxes;
  65940. if (boxes !== undefined && boxes !== null) {
  65941. for (index = 0, cache = boxes.length; index < cache; index++) {
  65942. var parsedBox = boxes[index];
  65943. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  65944. }
  65945. }
  65946. // Spheres
  65947. var spheres = geometries.spheres;
  65948. if (spheres !== undefined && spheres !== null) {
  65949. for (index = 0, cache = spheres.length; index < cache; index++) {
  65950. var parsedSphere = spheres[index];
  65951. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  65952. }
  65953. }
  65954. // Cylinders
  65955. var cylinders = geometries.cylinders;
  65956. if (cylinders !== undefined && cylinders !== null) {
  65957. for (index = 0, cache = cylinders.length; index < cache; index++) {
  65958. var parsedCylinder = cylinders[index];
  65959. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  65960. }
  65961. }
  65962. // Toruses
  65963. var toruses = geometries.toruses;
  65964. if (toruses !== undefined && toruses !== null) {
  65965. for (index = 0, cache = toruses.length; index < cache; index++) {
  65966. var parsedTorus = toruses[index];
  65967. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  65968. }
  65969. }
  65970. // Grounds
  65971. var grounds = geometries.grounds;
  65972. if (grounds !== undefined && grounds !== null) {
  65973. for (index = 0, cache = grounds.length; index < cache; index++) {
  65974. var parsedGround = grounds[index];
  65975. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  65976. }
  65977. }
  65978. // Planes
  65979. var planes = geometries.planes;
  65980. if (planes !== undefined && planes !== null) {
  65981. for (index = 0, cache = planes.length; index < cache; index++) {
  65982. var parsedPlane = planes[index];
  65983. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  65984. }
  65985. }
  65986. // TorusKnots
  65987. var torusKnots = geometries.torusKnots;
  65988. if (torusKnots !== undefined && torusKnots !== null) {
  65989. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  65990. var parsedTorusKnot = torusKnots[index];
  65991. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  65992. }
  65993. }
  65994. // VertexData
  65995. var vertexData = geometries.vertexData;
  65996. if (vertexData !== undefined && vertexData !== null) {
  65997. for (index = 0, cache = vertexData.length; index < cache; index++) {
  65998. var parsedVertexData = vertexData[index];
  65999. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  66000. }
  66001. }
  66002. addedGeometry.forEach(function (g) {
  66003. if (g) {
  66004. container.geometries.push(g);
  66005. }
  66006. });
  66007. }
  66008. // Transform nodes
  66009. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  66010. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  66011. var parsedTransformNode = parsedData.transformNodes[index];
  66012. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  66013. container.transformNodes.push(node);
  66014. }
  66015. }
  66016. // Meshes
  66017. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66018. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66019. var parsedMesh = parsedData.meshes[index];
  66020. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66021. container.meshes.push(mesh);
  66022. log += (index === 0 ? "\n\tMeshes:" : "");
  66023. log += "\n\t\t" + mesh.toString(fullDetails);
  66024. }
  66025. }
  66026. // Cameras
  66027. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  66028. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  66029. var parsedCamera = parsedData.cameras[index];
  66030. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  66031. container.cameras.push(camera);
  66032. log += (index === 0 ? "\n\tCameras:" : "");
  66033. log += "\n\t\t" + camera.toString(fullDetails);
  66034. }
  66035. }
  66036. // Browsing all the graph to connect the dots
  66037. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  66038. var camera = scene.cameras[index];
  66039. if (camera._waitingParentId) {
  66040. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  66041. camera._waitingParentId = null;
  66042. }
  66043. }
  66044. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66045. var light_1 = scene.lights[index];
  66046. if (light_1 && light_1._waitingParentId) {
  66047. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  66048. light_1._waitingParentId = null;
  66049. }
  66050. }
  66051. // Sounds
  66052. // TODO: add sound
  66053. var loadedSounds = [];
  66054. var loadedSound;
  66055. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  66056. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  66057. var parsedSound = parsedData.sounds[index];
  66058. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66059. if (!parsedSound.url)
  66060. parsedSound.url = parsedSound.name;
  66061. if (!loadedSounds[parsedSound.url]) {
  66062. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  66063. loadedSounds[parsedSound.url] = loadedSound;
  66064. container.sounds.push(loadedSound);
  66065. }
  66066. else {
  66067. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  66068. }
  66069. }
  66070. else {
  66071. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  66072. }
  66073. }
  66074. }
  66075. loadedSounds = [];
  66076. // Connect parents & children and parse actions
  66077. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  66078. var transformNode = scene.transformNodes[index];
  66079. if (transformNode._waitingParentId) {
  66080. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  66081. transformNode._waitingParentId = null;
  66082. }
  66083. }
  66084. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66085. var mesh = scene.meshes[index];
  66086. if (mesh._waitingParentId) {
  66087. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  66088. mesh._waitingParentId = null;
  66089. }
  66090. if (mesh._waitingActions) {
  66091. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  66092. mesh._waitingActions = null;
  66093. }
  66094. }
  66095. // freeze world matrix application
  66096. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66097. var currentMesh = scene.meshes[index];
  66098. if (currentMesh._waitingFreezeWorldMatrix) {
  66099. currentMesh.freezeWorldMatrix();
  66100. currentMesh._waitingFreezeWorldMatrix = null;
  66101. }
  66102. else {
  66103. currentMesh.computeWorldMatrix(true);
  66104. }
  66105. }
  66106. // Particles Systems
  66107. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66108. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66109. var parsedParticleSystem = parsedData.particleSystems[index];
  66110. if (parsedParticleSystem.activeParticleCount) {
  66111. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66112. container.particleSystems.push(ps);
  66113. }
  66114. else {
  66115. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66116. container.particleSystems.push(ps);
  66117. }
  66118. }
  66119. }
  66120. // Lens flares
  66121. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  66122. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  66123. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  66124. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  66125. container.lensFlareSystems.push(lf);
  66126. }
  66127. }
  66128. // Shadows
  66129. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  66130. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  66131. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  66132. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  66133. container.shadowGenerators.push(sg);
  66134. }
  66135. }
  66136. // Lights exclusions / inclusions
  66137. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66138. var light_2 = scene.lights[index];
  66139. // Excluded check
  66140. if (light_2._excludedMeshesIds.length > 0) {
  66141. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  66142. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  66143. if (excludedMesh) {
  66144. light_2.excludedMeshes.push(excludedMesh);
  66145. }
  66146. }
  66147. light_2._excludedMeshesIds = [];
  66148. }
  66149. // Included check
  66150. if (light_2._includedOnlyMeshesIds.length > 0) {
  66151. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  66152. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  66153. if (includedOnlyMesh) {
  66154. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  66155. }
  66156. }
  66157. light_2._includedOnlyMeshesIds = [];
  66158. }
  66159. }
  66160. // Effect layers
  66161. if (parsedData.effectLayers) {
  66162. for (index = 0; index < parsedData.effectLayers.length; index++) {
  66163. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  66164. container.effectLayers.push(effectLayer);
  66165. }
  66166. }
  66167. // Actions (scene)
  66168. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  66169. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  66170. }
  66171. if (!addToScene) {
  66172. container.removeAllFromScene();
  66173. }
  66174. }
  66175. catch (err) {
  66176. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  66177. if (onError) {
  66178. onError(msg, err);
  66179. }
  66180. else {
  66181. BABYLON.Tools.Log(msg);
  66182. throw err;
  66183. }
  66184. }
  66185. finally {
  66186. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66187. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66188. }
  66189. }
  66190. return container;
  66191. };
  66192. BABYLON.SceneLoader.RegisterPlugin({
  66193. name: "babylon.js",
  66194. extensions: ".babylon",
  66195. canDirectLoad: function (data) {
  66196. if (data.indexOf("babylon") !== -1) {
  66197. return true;
  66198. }
  66199. return false;
  66200. },
  66201. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  66202. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66203. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66204. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66205. // and avoid problems with multiple concurrent .babylon loads.
  66206. var log = "importMesh has failed JSON parse";
  66207. try {
  66208. var parsedData = JSON.parse(data);
  66209. log = "";
  66210. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66211. if (!meshesNames) {
  66212. meshesNames = null;
  66213. }
  66214. else if (!Array.isArray(meshesNames)) {
  66215. meshesNames = [meshesNames];
  66216. }
  66217. var hierarchyIds = new Array();
  66218. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66219. var loadedSkeletonsIds = [];
  66220. var loadedMaterialsIds = [];
  66221. var index;
  66222. var cache;
  66223. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66224. var parsedMesh = parsedData.meshes[index];
  66225. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  66226. if (meshesNames !== null) {
  66227. // Remove found mesh name from list.
  66228. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  66229. }
  66230. //Geometry?
  66231. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  66232. //does the file contain geometries?
  66233. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  66234. //find the correct geometry and add it to the scene
  66235. var found = false;
  66236. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  66237. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  66238. return;
  66239. }
  66240. else {
  66241. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  66242. if (parsedGeometryData.id === parsedMesh.geometryId) {
  66243. switch (geometryType) {
  66244. case "boxes":
  66245. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  66246. break;
  66247. case "spheres":
  66248. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  66249. break;
  66250. case "cylinders":
  66251. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  66252. break;
  66253. case "toruses":
  66254. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  66255. break;
  66256. case "grounds":
  66257. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  66258. break;
  66259. case "planes":
  66260. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  66261. break;
  66262. case "torusKnots":
  66263. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  66264. break;
  66265. case "vertexData":
  66266. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  66267. break;
  66268. }
  66269. found = true;
  66270. }
  66271. });
  66272. }
  66273. });
  66274. if (found === false) {
  66275. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  66276. }
  66277. }
  66278. }
  66279. // Material ?
  66280. if (parsedMesh.materialId) {
  66281. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  66282. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66283. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  66284. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  66285. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  66286. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  66287. var subMatId = parsedMultiMaterial.materials[matIndex];
  66288. loadedMaterialsIds.push(subMatId);
  66289. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  66290. if (mat) {
  66291. log += "\n\tMaterial " + mat.toString(fullDetails);
  66292. }
  66293. }
  66294. loadedMaterialsIds.push(parsedMultiMaterial.id);
  66295. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66296. if (mmat) {
  66297. materialFound = true;
  66298. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  66299. }
  66300. break;
  66301. }
  66302. }
  66303. }
  66304. if (materialFound === false) {
  66305. loadedMaterialsIds.push(parsedMesh.materialId);
  66306. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  66307. if (!mat) {
  66308. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  66309. }
  66310. else {
  66311. log += "\n\tMaterial " + mat.toString(fullDetails);
  66312. }
  66313. }
  66314. }
  66315. // Skeleton ?
  66316. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66317. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  66318. if (skeletonAlreadyLoaded === false) {
  66319. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  66320. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  66321. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  66322. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66323. skeletons.push(skeleton);
  66324. loadedSkeletonsIds.push(parsedSkeleton.id);
  66325. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  66326. }
  66327. }
  66328. }
  66329. }
  66330. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66331. meshes.push(mesh);
  66332. log += "\n\tMesh " + mesh.toString(fullDetails);
  66333. }
  66334. }
  66335. // Connecting parents
  66336. var currentMesh;
  66337. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66338. currentMesh = scene.meshes[index];
  66339. if (currentMesh._waitingParentId) {
  66340. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  66341. currentMesh._waitingParentId = null;
  66342. }
  66343. }
  66344. // freeze and compute world matrix application
  66345. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66346. currentMesh = scene.meshes[index];
  66347. if (currentMesh._waitingFreezeWorldMatrix) {
  66348. currentMesh.freezeWorldMatrix();
  66349. currentMesh._waitingFreezeWorldMatrix = null;
  66350. }
  66351. else {
  66352. currentMesh.computeWorldMatrix(true);
  66353. }
  66354. }
  66355. }
  66356. // Particles
  66357. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66358. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66359. var parsedParticleSystem = parsedData.particleSystems[index];
  66360. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  66361. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  66362. }
  66363. }
  66364. }
  66365. return true;
  66366. }
  66367. catch (err) {
  66368. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  66369. if (onError) {
  66370. onError(msg, err);
  66371. }
  66372. else {
  66373. BABYLON.Tools.Log(msg);
  66374. throw err;
  66375. }
  66376. }
  66377. finally {
  66378. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66379. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66380. }
  66381. }
  66382. return false;
  66383. },
  66384. load: function (scene, data, rootUrl, onError) {
  66385. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66386. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66387. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66388. // and avoid problems with multiple concurrent .babylon loads.
  66389. var log = "importScene has failed JSON parse";
  66390. try {
  66391. var parsedData = JSON.parse(data);
  66392. log = "";
  66393. // Scene
  66394. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  66395. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  66396. }
  66397. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  66398. scene.autoClear = parsedData.autoClear;
  66399. }
  66400. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  66401. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  66402. }
  66403. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  66404. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  66405. }
  66406. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  66407. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  66408. }
  66409. // Fog
  66410. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  66411. scene.fogMode = parsedData.fogMode;
  66412. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  66413. scene.fogStart = parsedData.fogStart;
  66414. scene.fogEnd = parsedData.fogEnd;
  66415. scene.fogDensity = parsedData.fogDensity;
  66416. log += "\tFog mode for scene: ";
  66417. switch (scene.fogMode) {
  66418. // getters not compiling, so using hardcoded
  66419. case 1:
  66420. log += "exp\n";
  66421. break;
  66422. case 2:
  66423. log += "exp2\n";
  66424. break;
  66425. case 3:
  66426. log += "linear\n";
  66427. break;
  66428. }
  66429. }
  66430. //Physics
  66431. if (parsedData.physicsEnabled) {
  66432. var physicsPlugin;
  66433. if (parsedData.physicsEngine === "cannon") {
  66434. physicsPlugin = new BABYLON.CannonJSPlugin();
  66435. }
  66436. else if (parsedData.physicsEngine === "oimo") {
  66437. physicsPlugin = new BABYLON.OimoJSPlugin();
  66438. }
  66439. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  66440. //else - default engine, which is currently oimo
  66441. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  66442. scene.enablePhysics(physicsGravity, physicsPlugin);
  66443. }
  66444. // Metadata
  66445. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  66446. scene.metadata = parsedData.metadata;
  66447. }
  66448. //collisions, if defined. otherwise, default is true
  66449. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  66450. scene.collisionsEnabled = parsedData.collisionsEnabled;
  66451. }
  66452. scene.workerCollisions = !!parsedData.workerCollisions;
  66453. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  66454. if (!container) {
  66455. return false;
  66456. }
  66457. if (parsedData.autoAnimate) {
  66458. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  66459. }
  66460. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  66461. scene.setActiveCameraByID(parsedData.activeCameraID);
  66462. }
  66463. // Environment texture
  66464. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  66465. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  66466. if (parsedData.createDefaultSkybox === true) {
  66467. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  66468. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  66469. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  66470. }
  66471. }
  66472. // Finish
  66473. return true;
  66474. }
  66475. catch (err) {
  66476. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  66477. if (onError) {
  66478. onError(msg, err);
  66479. }
  66480. else {
  66481. BABYLON.Tools.Log(msg);
  66482. throw err;
  66483. }
  66484. }
  66485. finally {
  66486. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66487. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66488. }
  66489. }
  66490. return false;
  66491. },
  66492. loadAssetContainer: function (scene, data, rootUrl, onError) {
  66493. var container = loadAssetContainer(scene, data, rootUrl, onError);
  66494. return container;
  66495. }
  66496. });
  66497. })(BABYLON || (BABYLON = {}));
  66498. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  66499. "use strict";
  66500. var BABYLON;
  66501. (function (BABYLON) {
  66502. var FilesInput = /** @class */ (function () {
  66503. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  66504. this.onProcessFileCallback = function () { return true; };
  66505. this._engine = engine;
  66506. this._currentScene = scene;
  66507. this._sceneLoadedCallback = sceneLoadedCallback;
  66508. this._progressCallback = progressCallback;
  66509. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  66510. this._textureLoadingCallback = textureLoadingCallback;
  66511. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  66512. this._onReloadCallback = onReloadCallback;
  66513. this._errorCallback = errorCallback;
  66514. }
  66515. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  66516. var _this = this;
  66517. if (elementToMonitor) {
  66518. this._elementToMonitor = elementToMonitor;
  66519. this._dragEnterHandler = function (e) { _this.drag(e); };
  66520. this._dragOverHandler = function (e) { _this.drag(e); };
  66521. this._dropHandler = function (e) { _this.drop(e); };
  66522. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  66523. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  66524. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  66525. }
  66526. };
  66527. FilesInput.prototype.dispose = function () {
  66528. if (!this._elementToMonitor) {
  66529. return;
  66530. }
  66531. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  66532. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  66533. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  66534. };
  66535. FilesInput.prototype.renderFunction = function () {
  66536. if (this._additionalRenderLoopLogicCallback) {
  66537. this._additionalRenderLoopLogicCallback();
  66538. }
  66539. if (this._currentScene) {
  66540. if (this._textureLoadingCallback) {
  66541. var remaining = this._currentScene.getWaitingItemsCount();
  66542. if (remaining > 0) {
  66543. this._textureLoadingCallback(remaining);
  66544. }
  66545. }
  66546. this._currentScene.render();
  66547. }
  66548. };
  66549. FilesInput.prototype.drag = function (e) {
  66550. e.stopPropagation();
  66551. e.preventDefault();
  66552. };
  66553. FilesInput.prototype.drop = function (eventDrop) {
  66554. eventDrop.stopPropagation();
  66555. eventDrop.preventDefault();
  66556. this.loadFiles(eventDrop);
  66557. };
  66558. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  66559. var _this = this;
  66560. var reader = folder.createReader();
  66561. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  66562. reader.readEntries(function (entries) {
  66563. remaining.count += entries.length;
  66564. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  66565. var entry = entries_1[_i];
  66566. if (entry.isFile) {
  66567. entry.file(function (file) {
  66568. file.correctName = relativePath + file.name;
  66569. files.push(file);
  66570. if (--remaining.count === 0) {
  66571. callback();
  66572. }
  66573. });
  66574. }
  66575. else if (entry.isDirectory) {
  66576. _this._traverseFolder(entry, files, remaining, callback);
  66577. }
  66578. }
  66579. if (--remaining.count) {
  66580. callback();
  66581. }
  66582. });
  66583. };
  66584. FilesInput.prototype._processFiles = function (files) {
  66585. for (var i = 0; i < files.length; i++) {
  66586. var name = files[i].correctName.toLowerCase();
  66587. var extension = name.split('.').pop();
  66588. if (!this.onProcessFileCallback(files[i], name, extension)) {
  66589. continue;
  66590. }
  66591. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  66592. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  66593. this._sceneFileToLoad = files[i];
  66594. }
  66595. else {
  66596. FilesInput.FilesToLoad[name] = files[i];
  66597. }
  66598. }
  66599. };
  66600. FilesInput.prototype.loadFiles = function (event) {
  66601. var _this = this;
  66602. if (this._startingProcessingFilesCallback)
  66603. this._startingProcessingFilesCallback();
  66604. // Handling data transfer via drag'n'drop
  66605. if (event && event.dataTransfer && event.dataTransfer.files) {
  66606. this._filesToLoad = event.dataTransfer.files;
  66607. }
  66608. // Handling files from input files
  66609. if (event && event.target && event.target.files) {
  66610. this._filesToLoad = event.target.files;
  66611. }
  66612. if (this._filesToLoad && this._filesToLoad.length > 0) {
  66613. var files_1 = new Array();
  66614. var folders = [];
  66615. var items = event.dataTransfer ? event.dataTransfer.items : null;
  66616. for (var i = 0; i < this._filesToLoad.length; i++) {
  66617. var fileToLoad = this._filesToLoad[i];
  66618. var name_1 = fileToLoad.name.toLowerCase();
  66619. var entry = void 0;
  66620. fileToLoad.correctName = name_1;
  66621. if (items) {
  66622. var item = items[i];
  66623. if (item.getAsEntry) {
  66624. entry = item.getAsEntry();
  66625. }
  66626. else if (item.webkitGetAsEntry) {
  66627. entry = item.webkitGetAsEntry();
  66628. }
  66629. }
  66630. if (!entry) {
  66631. files_1.push(fileToLoad);
  66632. }
  66633. else {
  66634. if (entry.isDirectory) {
  66635. folders.push(entry);
  66636. }
  66637. else {
  66638. files_1.push(fileToLoad);
  66639. }
  66640. }
  66641. }
  66642. if (folders.length === 0) {
  66643. this._processFiles(files_1);
  66644. this._processReload();
  66645. }
  66646. else {
  66647. var remaining = { count: folders.length };
  66648. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  66649. var folder = folders_1[_i];
  66650. this._traverseFolder(folder, files_1, remaining, function () {
  66651. _this._processFiles(files_1);
  66652. if (remaining.count === 0) {
  66653. _this._processReload();
  66654. }
  66655. });
  66656. }
  66657. }
  66658. }
  66659. };
  66660. FilesInput.prototype._processReload = function () {
  66661. if (this._onReloadCallback) {
  66662. this._onReloadCallback(this._sceneFileToLoad);
  66663. }
  66664. else {
  66665. this.reload();
  66666. }
  66667. };
  66668. FilesInput.prototype.reload = function () {
  66669. var _this = this;
  66670. // If a scene file has been provided
  66671. if (this._sceneFileToLoad) {
  66672. if (this._currentScene) {
  66673. if (BABYLON.Tools.errorsCount > 0) {
  66674. BABYLON.Tools.ClearLogCache();
  66675. }
  66676. this._engine.stopRenderLoop();
  66677. this._currentScene.dispose();
  66678. }
  66679. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  66680. if (_this._progressCallback) {
  66681. _this._progressCallback(progress);
  66682. }
  66683. }).then(function (scene) {
  66684. _this._currentScene = scene;
  66685. if (_this._sceneLoadedCallback) {
  66686. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  66687. }
  66688. // Wait for textures and shaders to be ready
  66689. _this._currentScene.executeWhenReady(function () {
  66690. _this._engine.runRenderLoop(function () {
  66691. _this.renderFunction();
  66692. });
  66693. });
  66694. }).catch(function (error) {
  66695. if (_this._errorCallback) {
  66696. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  66697. }
  66698. });
  66699. }
  66700. else {
  66701. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  66702. }
  66703. };
  66704. FilesInput.FilesToLoad = {};
  66705. return FilesInput;
  66706. }());
  66707. BABYLON.FilesInput = FilesInput;
  66708. })(BABYLON || (BABYLON = {}));
  66709. //# sourceMappingURL=babylon.filesInput.js.map
  66710. "use strict";
  66711. var BABYLON;
  66712. (function (BABYLON) {
  66713. /**
  66714. * This class implement a typical dictionary using a string as key and the generic type T as value.
  66715. * The underlying implementation relies on an associative array to ensure the best performances.
  66716. * The value can be anything including 'null' but except 'undefined'
  66717. */
  66718. var StringDictionary = /** @class */ (function () {
  66719. function StringDictionary() {
  66720. this._count = 0;
  66721. this._data = {};
  66722. }
  66723. /**
  66724. * This will clear this dictionary and copy the content from the 'source' one.
  66725. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  66726. * @param source the dictionary to take the content from and copy to this dictionary
  66727. */
  66728. StringDictionary.prototype.copyFrom = function (source) {
  66729. var _this = this;
  66730. this.clear();
  66731. source.forEach(function (t, v) { return _this.add(t, v); });
  66732. };
  66733. /**
  66734. * Get a value based from its key
  66735. * @param key the given key to get the matching value from
  66736. * @return the value if found, otherwise undefined is returned
  66737. */
  66738. StringDictionary.prototype.get = function (key) {
  66739. var val = this._data[key];
  66740. if (val !== undefined) {
  66741. return val;
  66742. }
  66743. return undefined;
  66744. };
  66745. /**
  66746. * Get a value from its key or add it if it doesn't exist.
  66747. * This method will ensure you that a given key/data will be present in the dictionary.
  66748. * @param key the given key to get the matching value from
  66749. * @param factory the factory that will create the value if the key is not present in the dictionary.
  66750. * The factory will only be invoked if there's no data for the given key.
  66751. * @return the value corresponding to the key.
  66752. */
  66753. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  66754. var val = this.get(key);
  66755. if (val !== undefined) {
  66756. return val;
  66757. }
  66758. val = factory(key);
  66759. if (val) {
  66760. this.add(key, val);
  66761. }
  66762. return val;
  66763. };
  66764. /**
  66765. * Get a value from its key if present in the dictionary otherwise add it
  66766. * @param key the key to get the value from
  66767. * @param val if there's no such key/value pair in the dictionary add it with this value
  66768. * @return the value corresponding to the key
  66769. */
  66770. StringDictionary.prototype.getOrAdd = function (key, val) {
  66771. var curVal = this.get(key);
  66772. if (curVal !== undefined) {
  66773. return curVal;
  66774. }
  66775. this.add(key, val);
  66776. return val;
  66777. };
  66778. /**
  66779. * Check if there's a given key in the dictionary
  66780. * @param key the key to check for
  66781. * @return true if the key is present, false otherwise
  66782. */
  66783. StringDictionary.prototype.contains = function (key) {
  66784. return this._data[key] !== undefined;
  66785. };
  66786. /**
  66787. * Add a new key and its corresponding value
  66788. * @param key the key to add
  66789. * @param value the value corresponding to the key
  66790. * @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
  66791. */
  66792. StringDictionary.prototype.add = function (key, value) {
  66793. if (this._data[key] !== undefined) {
  66794. return false;
  66795. }
  66796. this._data[key] = value;
  66797. ++this._count;
  66798. return true;
  66799. };
  66800. StringDictionary.prototype.set = function (key, value) {
  66801. if (this._data[key] === undefined) {
  66802. return false;
  66803. }
  66804. this._data[key] = value;
  66805. return true;
  66806. };
  66807. /**
  66808. * Get the element of the given key and remove it from the dictionary
  66809. * @param key
  66810. */
  66811. StringDictionary.prototype.getAndRemove = function (key) {
  66812. var val = this.get(key);
  66813. if (val !== undefined) {
  66814. delete this._data[key];
  66815. --this._count;
  66816. return val;
  66817. }
  66818. return null;
  66819. };
  66820. /**
  66821. * Remove a key/value from the dictionary.
  66822. * @param key the key to remove
  66823. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  66824. */
  66825. StringDictionary.prototype.remove = function (key) {
  66826. if (this.contains(key)) {
  66827. delete this._data[key];
  66828. --this._count;
  66829. return true;
  66830. }
  66831. return false;
  66832. };
  66833. /**
  66834. * Clear the whole content of the dictionary
  66835. */
  66836. StringDictionary.prototype.clear = function () {
  66837. this._data = {};
  66838. this._count = 0;
  66839. };
  66840. Object.defineProperty(StringDictionary.prototype, "count", {
  66841. get: function () {
  66842. return this._count;
  66843. },
  66844. enumerable: true,
  66845. configurable: true
  66846. });
  66847. /**
  66848. * Execute a callback on each key/val of the dictionary.
  66849. * Note that you can remove any element in this dictionary in the callback implementation
  66850. * @param callback the callback to execute on a given key/value pair
  66851. */
  66852. StringDictionary.prototype.forEach = function (callback) {
  66853. for (var cur in this._data) {
  66854. var val = this._data[cur];
  66855. callback(cur, val);
  66856. }
  66857. };
  66858. /**
  66859. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  66860. * If the callback returns null or undefined the method will iterate to the next key/value pair
  66861. * Note that you can remove any element in this dictionary in the callback implementation
  66862. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  66863. */
  66864. StringDictionary.prototype.first = function (callback) {
  66865. for (var cur in this._data) {
  66866. var val = this._data[cur];
  66867. var res = callback(cur, val);
  66868. if (res) {
  66869. return res;
  66870. }
  66871. }
  66872. return null;
  66873. };
  66874. return StringDictionary;
  66875. }());
  66876. BABYLON.StringDictionary = StringDictionary;
  66877. })(BABYLON || (BABYLON = {}));
  66878. //# sourceMappingURL=babylon.stringDictionary.js.map
  66879. "use strict";
  66880. var BABYLON;
  66881. (function (BABYLON) {
  66882. var Tags = /** @class */ (function () {
  66883. function Tags() {
  66884. }
  66885. Tags.EnableFor = function (obj) {
  66886. obj._tags = obj._tags || {};
  66887. obj.hasTags = function () {
  66888. return Tags.HasTags(obj);
  66889. };
  66890. obj.addTags = function (tagsString) {
  66891. return Tags.AddTagsTo(obj, tagsString);
  66892. };
  66893. obj.removeTags = function (tagsString) {
  66894. return Tags.RemoveTagsFrom(obj, tagsString);
  66895. };
  66896. obj.matchesTagsQuery = function (tagsQuery) {
  66897. return Tags.MatchesQuery(obj, tagsQuery);
  66898. };
  66899. };
  66900. Tags.DisableFor = function (obj) {
  66901. delete obj._tags;
  66902. delete obj.hasTags;
  66903. delete obj.addTags;
  66904. delete obj.removeTags;
  66905. delete obj.matchesTagsQuery;
  66906. };
  66907. Tags.HasTags = function (obj) {
  66908. if (!obj._tags) {
  66909. return false;
  66910. }
  66911. return !BABYLON.Tools.IsEmpty(obj._tags);
  66912. };
  66913. Tags.GetTags = function (obj, asString) {
  66914. if (asString === void 0) { asString = true; }
  66915. if (!obj._tags) {
  66916. return null;
  66917. }
  66918. if (asString) {
  66919. var tagsArray = [];
  66920. for (var tag in obj._tags) {
  66921. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  66922. tagsArray.push(tag);
  66923. }
  66924. }
  66925. return tagsArray.join(" ");
  66926. }
  66927. else {
  66928. return obj._tags;
  66929. }
  66930. };
  66931. // the tags 'true' and 'false' are reserved and cannot be used as tags
  66932. // a tag cannot start with '||', '&&', and '!'
  66933. // it cannot contain whitespaces
  66934. Tags.AddTagsTo = function (obj, tagsString) {
  66935. if (!tagsString) {
  66936. return;
  66937. }
  66938. if (typeof tagsString !== "string") {
  66939. return;
  66940. }
  66941. var tags = tagsString.split(" ");
  66942. tags.forEach(function (tag, index, array) {
  66943. Tags._AddTagTo(obj, tag);
  66944. });
  66945. };
  66946. Tags._AddTagTo = function (obj, tag) {
  66947. tag = tag.trim();
  66948. if (tag === "" || tag === "true" || tag === "false") {
  66949. return;
  66950. }
  66951. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  66952. return;
  66953. }
  66954. Tags.EnableFor(obj);
  66955. obj._tags[tag] = true;
  66956. };
  66957. Tags.RemoveTagsFrom = function (obj, tagsString) {
  66958. if (!Tags.HasTags(obj)) {
  66959. return;
  66960. }
  66961. var tags = tagsString.split(" ");
  66962. for (var t in tags) {
  66963. Tags._RemoveTagFrom(obj, tags[t]);
  66964. }
  66965. };
  66966. Tags._RemoveTagFrom = function (obj, tag) {
  66967. delete obj._tags[tag];
  66968. };
  66969. Tags.MatchesQuery = function (obj, tagsQuery) {
  66970. if (tagsQuery === undefined) {
  66971. return true;
  66972. }
  66973. if (tagsQuery === "") {
  66974. return Tags.HasTags(obj);
  66975. }
  66976. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  66977. };
  66978. return Tags;
  66979. }());
  66980. BABYLON.Tags = Tags;
  66981. })(BABYLON || (BABYLON = {}));
  66982. //# sourceMappingURL=babylon.tags.js.map
  66983. "use strict";
  66984. var BABYLON;
  66985. (function (BABYLON) {
  66986. var AndOrNotEvaluator = /** @class */ (function () {
  66987. function AndOrNotEvaluator() {
  66988. }
  66989. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  66990. if (!query.match(/\([^\(\)]*\)/g)) {
  66991. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  66992. }
  66993. else {
  66994. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  66995. // remove parenthesis
  66996. r = r.slice(1, r.length - 1);
  66997. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  66998. });
  66999. }
  67000. if (query === "true") {
  67001. return true;
  67002. }
  67003. if (query === "false") {
  67004. return false;
  67005. }
  67006. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  67007. };
  67008. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  67009. evaluateCallback = evaluateCallback || (function (r) {
  67010. return r === "true" ? true : false;
  67011. });
  67012. var result;
  67013. var or = parenthesisContent.split("||");
  67014. for (var i in or) {
  67015. if (or.hasOwnProperty(i)) {
  67016. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  67017. var and = ori.split("&&");
  67018. if (and.length > 1) {
  67019. for (var j = 0; j < and.length; ++j) {
  67020. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  67021. if (andj !== "true" && andj !== "false") {
  67022. if (andj[0] === "!") {
  67023. result = !evaluateCallback(andj.substring(1));
  67024. }
  67025. else {
  67026. result = evaluateCallback(andj);
  67027. }
  67028. }
  67029. else {
  67030. result = andj === "true" ? true : false;
  67031. }
  67032. if (!result) {
  67033. ori = "false";
  67034. break;
  67035. }
  67036. }
  67037. }
  67038. if (result || ori === "true") {
  67039. result = true;
  67040. break;
  67041. }
  67042. // result equals false (or undefined)
  67043. if (ori !== "true" && ori !== "false") {
  67044. if (ori[0] === "!") {
  67045. result = !evaluateCallback(ori.substring(1));
  67046. }
  67047. else {
  67048. result = evaluateCallback(ori);
  67049. }
  67050. }
  67051. else {
  67052. result = ori === "true" ? true : false;
  67053. }
  67054. }
  67055. }
  67056. // the whole parenthesis scope is replaced by 'true' or 'false'
  67057. return result ? "true" : "false";
  67058. };
  67059. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  67060. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  67061. // remove whitespaces
  67062. r = r.replace(/[\s]/g, function () { return ""; });
  67063. return r.length % 2 ? "!" : "";
  67064. });
  67065. booleanString = booleanString.trim();
  67066. if (booleanString === "!true") {
  67067. booleanString = "false";
  67068. }
  67069. else if (booleanString === "!false") {
  67070. booleanString = "true";
  67071. }
  67072. return booleanString;
  67073. };
  67074. return AndOrNotEvaluator;
  67075. }());
  67076. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  67077. })(BABYLON || (BABYLON = {}));
  67078. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  67079. "use strict";
  67080. var BABYLON;
  67081. (function (BABYLON) {
  67082. var Database = /** @class */ (function () {
  67083. function Database(urlToScene, callbackManifestChecked) {
  67084. // Handling various flavors of prefixed version of IndexedDB
  67085. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  67086. this.callbackManifestChecked = callbackManifestChecked;
  67087. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  67088. this.db = null;
  67089. this._enableSceneOffline = false;
  67090. this._enableTexturesOffline = false;
  67091. this.manifestVersionFound = 0;
  67092. this.mustUpdateRessources = false;
  67093. this.hasReachedQuota = false;
  67094. if (!Database.IDBStorageEnabled) {
  67095. this.callbackManifestChecked(true);
  67096. }
  67097. else {
  67098. this.checkManifestFile();
  67099. }
  67100. }
  67101. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  67102. get: function () {
  67103. return this._enableSceneOffline;
  67104. },
  67105. enumerable: true,
  67106. configurable: true
  67107. });
  67108. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  67109. get: function () {
  67110. return this._enableTexturesOffline;
  67111. },
  67112. enumerable: true,
  67113. configurable: true
  67114. });
  67115. Database.prototype.checkManifestFile = function () {
  67116. var _this = this;
  67117. var noManifestFile = function () {
  67118. _this._enableSceneOffline = false;
  67119. _this._enableTexturesOffline = false;
  67120. _this.callbackManifestChecked(false);
  67121. };
  67122. var timeStampUsed = false;
  67123. var manifestURL = this.currentSceneUrl + ".manifest";
  67124. var xhr = new XMLHttpRequest();
  67125. if (navigator.onLine) {
  67126. // Adding a timestamp to by-pass browsers' cache
  67127. timeStampUsed = true;
  67128. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  67129. }
  67130. xhr.open("GET", manifestURL, true);
  67131. xhr.addEventListener("load", function () {
  67132. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  67133. try {
  67134. var manifestFile = JSON.parse(xhr.response);
  67135. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  67136. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  67137. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  67138. _this.manifestVersionFound = manifestFile.version;
  67139. }
  67140. if (_this.callbackManifestChecked) {
  67141. _this.callbackManifestChecked(true);
  67142. }
  67143. }
  67144. catch (ex) {
  67145. noManifestFile();
  67146. }
  67147. }
  67148. else {
  67149. noManifestFile();
  67150. }
  67151. }, false);
  67152. xhr.addEventListener("error", function (event) {
  67153. if (timeStampUsed) {
  67154. timeStampUsed = false;
  67155. // Let's retry without the timeStamp
  67156. // It could fail when coupled with HTML5 Offline API
  67157. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  67158. xhr.open("GET", retryManifestURL, true);
  67159. xhr.send();
  67160. }
  67161. else {
  67162. noManifestFile();
  67163. }
  67164. }, false);
  67165. try {
  67166. xhr.send();
  67167. }
  67168. catch (ex) {
  67169. BABYLON.Tools.Error("Error on XHR send request.");
  67170. this.callbackManifestChecked(false);
  67171. }
  67172. };
  67173. Database.prototype.openAsync = function (successCallback, errorCallback) {
  67174. var _this = this;
  67175. var handleError = function () {
  67176. _this.isSupported = false;
  67177. if (errorCallback)
  67178. errorCallback();
  67179. };
  67180. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  67181. // Your browser doesn't support IndexedDB
  67182. this.isSupported = false;
  67183. if (errorCallback)
  67184. errorCallback();
  67185. }
  67186. else {
  67187. // If the DB hasn't been opened or created yet
  67188. if (!this.db) {
  67189. this.hasReachedQuota = false;
  67190. this.isSupported = true;
  67191. var request = this.idbFactory.open("babylonjs", 1);
  67192. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  67193. request.onerror = function (event) {
  67194. handleError();
  67195. };
  67196. // executes when a version change transaction cannot complete due to other active transactions
  67197. request.onblocked = function (event) {
  67198. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  67199. handleError();
  67200. };
  67201. // DB has been opened successfully
  67202. request.onsuccess = function (event) {
  67203. _this.db = request.result;
  67204. successCallback();
  67205. };
  67206. // Initialization of the DB. Creating Scenes & Textures stores
  67207. request.onupgradeneeded = function (event) {
  67208. _this.db = (event.target).result;
  67209. if (_this.db) {
  67210. try {
  67211. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  67212. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  67213. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  67214. }
  67215. catch (ex) {
  67216. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  67217. handleError();
  67218. }
  67219. }
  67220. };
  67221. }
  67222. else {
  67223. if (successCallback)
  67224. successCallback();
  67225. }
  67226. }
  67227. };
  67228. Database.prototype.loadImageFromDB = function (url, image) {
  67229. var _this = this;
  67230. var completeURL = Database.ReturnFullUrlLocation(url);
  67231. var saveAndLoadImage = function () {
  67232. if (!_this.hasReachedQuota && _this.db !== null) {
  67233. // the texture is not yet in the DB, let's try to save it
  67234. _this._saveImageIntoDBAsync(completeURL, image);
  67235. }
  67236. else {
  67237. image.src = url;
  67238. }
  67239. };
  67240. if (!this.mustUpdateRessources) {
  67241. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  67242. }
  67243. else {
  67244. saveAndLoadImage();
  67245. }
  67246. };
  67247. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  67248. if (this.isSupported && this.db !== null) {
  67249. var texture;
  67250. var transaction = this.db.transaction(["textures"]);
  67251. transaction.onabort = function (event) {
  67252. image.src = url;
  67253. };
  67254. transaction.oncomplete = function (event) {
  67255. var blobTextureURL;
  67256. if (texture) {
  67257. var URL = window.URL || window.webkitURL;
  67258. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  67259. image.onerror = function () {
  67260. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  67261. image.src = url;
  67262. };
  67263. image.src = blobTextureURL;
  67264. }
  67265. else {
  67266. notInDBCallback();
  67267. }
  67268. };
  67269. var getRequest = transaction.objectStore("textures").get(url);
  67270. getRequest.onsuccess = function (event) {
  67271. texture = (event.target).result;
  67272. };
  67273. getRequest.onerror = function (event) {
  67274. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  67275. image.src = url;
  67276. };
  67277. }
  67278. else {
  67279. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67280. image.src = url;
  67281. }
  67282. };
  67283. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  67284. var _this = this;
  67285. if (this.isSupported) {
  67286. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  67287. var generateBlobUrl = function () {
  67288. var blobTextureURL;
  67289. if (blob) {
  67290. var URL = window.URL || window.webkitURL;
  67291. try {
  67292. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  67293. }
  67294. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  67295. catch (ex) {
  67296. blobTextureURL = URL.createObjectURL(blob);
  67297. }
  67298. }
  67299. if (blobTextureURL) {
  67300. image.src = blobTextureURL;
  67301. }
  67302. };
  67303. if (Database.IsUASupportingBlobStorage) {
  67304. var xhr = new XMLHttpRequest(), blob;
  67305. xhr.open("GET", url, true);
  67306. xhr.responseType = "blob";
  67307. xhr.addEventListener("load", function () {
  67308. if (xhr.status === 200 && _this.db) {
  67309. // Blob as response (XHR2)
  67310. blob = xhr.response;
  67311. var transaction = _this.db.transaction(["textures"], "readwrite");
  67312. // the transaction could abort because of a QuotaExceededError error
  67313. transaction.onabort = function (event) {
  67314. try {
  67315. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67316. var srcElement = (event.srcElement || event.target);
  67317. var error = srcElement.error;
  67318. if (error && error.name === "QuotaExceededError") {
  67319. _this.hasReachedQuota = true;
  67320. }
  67321. }
  67322. catch (ex) { }
  67323. generateBlobUrl();
  67324. };
  67325. transaction.oncomplete = function (event) {
  67326. generateBlobUrl();
  67327. };
  67328. var newTexture = { textureUrl: url, data: blob };
  67329. try {
  67330. // Put the blob into the dabase
  67331. var addRequest = transaction.objectStore("textures").put(newTexture);
  67332. addRequest.onsuccess = function (event) {
  67333. };
  67334. addRequest.onerror = function (event) {
  67335. generateBlobUrl();
  67336. };
  67337. }
  67338. catch (ex) {
  67339. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  67340. if (ex.code === 25) {
  67341. Database.IsUASupportingBlobStorage = false;
  67342. }
  67343. image.src = url;
  67344. }
  67345. }
  67346. else {
  67347. image.src = url;
  67348. }
  67349. }, false);
  67350. xhr.addEventListener("error", function (event) {
  67351. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  67352. image.src = url;
  67353. }, false);
  67354. xhr.send();
  67355. }
  67356. else {
  67357. image.src = url;
  67358. }
  67359. }
  67360. else {
  67361. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67362. image.src = url;
  67363. }
  67364. };
  67365. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  67366. var _this = this;
  67367. var updateVersion = function () {
  67368. // the version is not yet in the DB or we need to update it
  67369. _this._saveVersionIntoDBAsync(url, versionLoaded);
  67370. };
  67371. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  67372. };
  67373. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  67374. var _this = this;
  67375. if (this.isSupported && this.db) {
  67376. var version;
  67377. try {
  67378. var transaction = this.db.transaction(["versions"]);
  67379. transaction.oncomplete = function (event) {
  67380. if (version) {
  67381. // If the version in the JSON file is > than the version in DB
  67382. if (_this.manifestVersionFound > version.data) {
  67383. _this.mustUpdateRessources = true;
  67384. updateInDBCallback();
  67385. }
  67386. else {
  67387. callback(version.data);
  67388. }
  67389. }
  67390. else {
  67391. _this.mustUpdateRessources = true;
  67392. updateInDBCallback();
  67393. }
  67394. };
  67395. transaction.onabort = function (event) {
  67396. callback(-1);
  67397. };
  67398. var getRequest = transaction.objectStore("versions").get(url);
  67399. getRequest.onsuccess = function (event) {
  67400. version = (event.target).result;
  67401. };
  67402. getRequest.onerror = function (event) {
  67403. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  67404. callback(-1);
  67405. };
  67406. }
  67407. catch (ex) {
  67408. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  67409. callback(-1);
  67410. }
  67411. }
  67412. else {
  67413. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67414. callback(-1);
  67415. }
  67416. };
  67417. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  67418. var _this = this;
  67419. if (this.isSupported && !this.hasReachedQuota && this.db) {
  67420. try {
  67421. // Open a transaction to the database
  67422. var transaction = this.db.transaction(["versions"], "readwrite");
  67423. // the transaction could abort because of a QuotaExceededError error
  67424. transaction.onabort = function (event) {
  67425. try {
  67426. var error = event.srcElement['error'];
  67427. if (error && error.name === "QuotaExceededError") {
  67428. _this.hasReachedQuota = true;
  67429. }
  67430. }
  67431. catch (ex) { }
  67432. callback(-1);
  67433. };
  67434. transaction.oncomplete = function (event) {
  67435. callback(_this.manifestVersionFound);
  67436. };
  67437. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  67438. // Put the scene into the database
  67439. var addRequest = transaction.objectStore("versions").put(newVersion);
  67440. addRequest.onsuccess = function (event) {
  67441. };
  67442. addRequest.onerror = function (event) {
  67443. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  67444. };
  67445. }
  67446. catch (ex) {
  67447. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  67448. callback(-1);
  67449. }
  67450. }
  67451. else {
  67452. callback(-1);
  67453. }
  67454. };
  67455. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  67456. var _this = this;
  67457. var completeUrl = Database.ReturnFullUrlLocation(url);
  67458. var saveAndLoadFile = function () {
  67459. // the scene is not yet in the DB, let's try to save it
  67460. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  67461. };
  67462. this._checkVersionFromDB(completeUrl, function (version) {
  67463. if (version !== -1) {
  67464. if (!_this.mustUpdateRessources) {
  67465. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  67466. }
  67467. else {
  67468. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  67469. }
  67470. }
  67471. else {
  67472. if (errorCallback) {
  67473. errorCallback();
  67474. }
  67475. }
  67476. });
  67477. };
  67478. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  67479. if (this.isSupported && this.db) {
  67480. var targetStore;
  67481. if (url.indexOf(".babylon") !== -1) {
  67482. targetStore = "scenes";
  67483. }
  67484. else {
  67485. targetStore = "textures";
  67486. }
  67487. var file;
  67488. var transaction = this.db.transaction([targetStore]);
  67489. transaction.oncomplete = function (event) {
  67490. if (file) {
  67491. callback(file.data);
  67492. }
  67493. else {
  67494. notInDBCallback();
  67495. }
  67496. };
  67497. transaction.onabort = function (event) {
  67498. notInDBCallback();
  67499. };
  67500. var getRequest = transaction.objectStore(targetStore).get(url);
  67501. getRequest.onsuccess = function (event) {
  67502. file = (event.target).result;
  67503. };
  67504. getRequest.onerror = function (event) {
  67505. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  67506. notInDBCallback();
  67507. };
  67508. }
  67509. else {
  67510. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67511. callback();
  67512. }
  67513. };
  67514. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  67515. var _this = this;
  67516. if (this.isSupported) {
  67517. var targetStore;
  67518. if (url.indexOf(".babylon") !== -1) {
  67519. targetStore = "scenes";
  67520. }
  67521. else {
  67522. targetStore = "textures";
  67523. }
  67524. // Create XHR
  67525. var xhr = new XMLHttpRequest();
  67526. var fileData;
  67527. xhr.open("GET", url, true);
  67528. if (useArrayBuffer) {
  67529. xhr.responseType = "arraybuffer";
  67530. }
  67531. if (progressCallback) {
  67532. xhr.onprogress = progressCallback;
  67533. }
  67534. xhr.addEventListener("load", function () {
  67535. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  67536. // Blob as response (XHR2)
  67537. //fileData = xhr.responseText;
  67538. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  67539. if (!_this.hasReachedQuota && _this.db) {
  67540. // Open a transaction to the database
  67541. var transaction = _this.db.transaction([targetStore], "readwrite");
  67542. // the transaction could abort because of a QuotaExceededError error
  67543. transaction.onabort = function (event) {
  67544. try {
  67545. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67546. var error = event.srcElement['error'];
  67547. if (error && error.name === "QuotaExceededError") {
  67548. _this.hasReachedQuota = true;
  67549. }
  67550. }
  67551. catch (ex) { }
  67552. callback(fileData);
  67553. };
  67554. transaction.oncomplete = function (event) {
  67555. callback(fileData);
  67556. };
  67557. var newFile;
  67558. if (targetStore === "scenes") {
  67559. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  67560. }
  67561. else {
  67562. newFile = { textureUrl: url, data: fileData };
  67563. }
  67564. try {
  67565. // Put the scene into the database
  67566. var addRequest = transaction.objectStore(targetStore).put(newFile);
  67567. addRequest.onsuccess = function (event) {
  67568. };
  67569. addRequest.onerror = function (event) {
  67570. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  67571. };
  67572. }
  67573. catch (ex) {
  67574. callback(fileData);
  67575. }
  67576. }
  67577. else {
  67578. callback(fileData);
  67579. }
  67580. }
  67581. else {
  67582. callback();
  67583. }
  67584. }, false);
  67585. xhr.addEventListener("error", function (event) {
  67586. BABYLON.Tools.Error("error on XHR request.");
  67587. callback();
  67588. }, false);
  67589. xhr.send();
  67590. }
  67591. else {
  67592. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67593. callback();
  67594. }
  67595. };
  67596. Database.IsUASupportingBlobStorage = true;
  67597. Database.IDBStorageEnabled = true;
  67598. Database.parseURL = function (url) {
  67599. var a = document.createElement('a');
  67600. a.href = url;
  67601. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  67602. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  67603. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  67604. return absLocation;
  67605. };
  67606. Database.ReturnFullUrlLocation = function (url) {
  67607. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  67608. return (Database.parseURL(window.location.href) + url);
  67609. }
  67610. else {
  67611. return url;
  67612. }
  67613. };
  67614. return Database;
  67615. }());
  67616. BABYLON.Database = Database;
  67617. })(BABYLON || (BABYLON = {}));
  67618. //# sourceMappingURL=babylon.database.js.map
  67619. "use strict";
  67620. var BABYLON;
  67621. (function (BABYLON) {
  67622. var FresnelParameters = /** @class */ (function () {
  67623. function FresnelParameters() {
  67624. this._isEnabled = true;
  67625. this.leftColor = BABYLON.Color3.White();
  67626. this.rightColor = BABYLON.Color3.Black();
  67627. this.bias = 0;
  67628. this.power = 1;
  67629. }
  67630. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  67631. get: function () {
  67632. return this._isEnabled;
  67633. },
  67634. set: function (value) {
  67635. if (this._isEnabled === value) {
  67636. return;
  67637. }
  67638. this._isEnabled = value;
  67639. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  67640. },
  67641. enumerable: true,
  67642. configurable: true
  67643. });
  67644. FresnelParameters.prototype.clone = function () {
  67645. var newFresnelParameters = new FresnelParameters();
  67646. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  67647. return newFresnelParameters;
  67648. };
  67649. FresnelParameters.prototype.serialize = function () {
  67650. var serializationObject = {};
  67651. serializationObject.isEnabled = this.isEnabled;
  67652. serializationObject.leftColor = this.leftColor.asArray();
  67653. serializationObject.rightColor = this.rightColor.asArray();
  67654. serializationObject.bias = this.bias;
  67655. serializationObject.power = this.power;
  67656. return serializationObject;
  67657. };
  67658. FresnelParameters.Parse = function (parsedFresnelParameters) {
  67659. var fresnelParameters = new FresnelParameters();
  67660. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  67661. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  67662. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  67663. fresnelParameters.bias = parsedFresnelParameters.bias;
  67664. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  67665. return fresnelParameters;
  67666. };
  67667. return FresnelParameters;
  67668. }());
  67669. BABYLON.FresnelParameters = FresnelParameters;
  67670. })(BABYLON || (BABYLON = {}));
  67671. //# sourceMappingURL=babylon.fresnelParameters.js.map
  67672. "use strict";
  67673. var BABYLON;
  67674. (function (BABYLON) {
  67675. var MultiMaterial = /** @class */ (function (_super) {
  67676. __extends(MultiMaterial, _super);
  67677. function MultiMaterial(name, scene) {
  67678. var _this = _super.call(this, name, scene, true) || this;
  67679. scene.multiMaterials.push(_this);
  67680. _this.subMaterials = new Array();
  67681. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  67682. return _this;
  67683. }
  67684. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  67685. get: function () {
  67686. return this._subMaterials;
  67687. },
  67688. set: function (value) {
  67689. this._subMaterials = value;
  67690. this._hookArray(value);
  67691. },
  67692. enumerable: true,
  67693. configurable: true
  67694. });
  67695. MultiMaterial.prototype._hookArray = function (array) {
  67696. var _this = this;
  67697. var oldPush = array.push;
  67698. array.push = function () {
  67699. var items = [];
  67700. for (var _i = 0; _i < arguments.length; _i++) {
  67701. items[_i] = arguments[_i];
  67702. }
  67703. var result = oldPush.apply(array, items);
  67704. _this._markAllSubMeshesAsTexturesDirty();
  67705. return result;
  67706. };
  67707. var oldSplice = array.splice;
  67708. array.splice = function (index, deleteCount) {
  67709. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67710. _this._markAllSubMeshesAsTexturesDirty();
  67711. return deleted;
  67712. };
  67713. };
  67714. // Properties
  67715. MultiMaterial.prototype.getSubMaterial = function (index) {
  67716. if (index < 0 || index >= this.subMaterials.length) {
  67717. return this.getScene().defaultMaterial;
  67718. }
  67719. return this.subMaterials[index];
  67720. };
  67721. MultiMaterial.prototype.getActiveTextures = function () {
  67722. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  67723. if (subMaterial) {
  67724. return subMaterial.getActiveTextures();
  67725. }
  67726. else {
  67727. return [];
  67728. }
  67729. }));
  67730. var _a;
  67731. };
  67732. // Methods
  67733. MultiMaterial.prototype.getClassName = function () {
  67734. return "MultiMaterial";
  67735. };
  67736. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  67737. for (var index = 0; index < this.subMaterials.length; index++) {
  67738. var subMaterial = this.subMaterials[index];
  67739. if (subMaterial) {
  67740. if (subMaterial.storeEffectOnSubMeshes) {
  67741. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  67742. return false;
  67743. }
  67744. continue;
  67745. }
  67746. if (!subMaterial.isReady(mesh)) {
  67747. return false;
  67748. }
  67749. }
  67750. }
  67751. return true;
  67752. };
  67753. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  67754. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  67755. for (var index = 0; index < this.subMaterials.length; index++) {
  67756. var subMaterial = null;
  67757. var current = this.subMaterials[index];
  67758. if (cloneChildren && current) {
  67759. subMaterial = current.clone(name + "-" + current.name);
  67760. }
  67761. else {
  67762. subMaterial = this.subMaterials[index];
  67763. }
  67764. newMultiMaterial.subMaterials.push(subMaterial);
  67765. }
  67766. return newMultiMaterial;
  67767. };
  67768. MultiMaterial.prototype.serialize = function () {
  67769. var serializationObject = {};
  67770. serializationObject.name = this.name;
  67771. serializationObject.id = this.id;
  67772. if (BABYLON.Tags) {
  67773. serializationObject.tags = BABYLON.Tags.GetTags(this);
  67774. }
  67775. serializationObject.materials = [];
  67776. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  67777. var subMat = this.subMaterials[matIndex];
  67778. if (subMat) {
  67779. serializationObject.materials.push(subMat.id);
  67780. }
  67781. else {
  67782. serializationObject.materials.push(null);
  67783. }
  67784. }
  67785. return serializationObject;
  67786. };
  67787. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  67788. var scene = this.getScene();
  67789. if (!scene) {
  67790. return;
  67791. }
  67792. var index = scene.multiMaterials.indexOf(this);
  67793. if (index >= 0) {
  67794. scene.multiMaterials.splice(index, 1);
  67795. }
  67796. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  67797. };
  67798. return MultiMaterial;
  67799. }(BABYLON.Material));
  67800. BABYLON.MultiMaterial = MultiMaterial;
  67801. })(BABYLON || (BABYLON = {}));
  67802. //# sourceMappingURL=babylon.multiMaterial.js.map
  67803. "use strict";
  67804. var BABYLON;
  67805. (function (BABYLON) {
  67806. var FreeCameraTouchInput = /** @class */ (function () {
  67807. function FreeCameraTouchInput() {
  67808. this._offsetX = null;
  67809. this._offsetY = null;
  67810. this._pointerPressed = new Array();
  67811. this.touchAngularSensibility = 200000.0;
  67812. this.touchMoveSensibility = 250.0;
  67813. }
  67814. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  67815. var _this = this;
  67816. var previousPosition = null;
  67817. if (this._pointerInput === undefined) {
  67818. this._onLostFocus = function (evt) {
  67819. _this._offsetX = null;
  67820. _this._offsetY = null;
  67821. };
  67822. this._pointerInput = function (p, s) {
  67823. var evt = p.event;
  67824. if (evt.pointerType === "mouse") {
  67825. return;
  67826. }
  67827. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  67828. if (!noPreventDefault) {
  67829. evt.preventDefault();
  67830. }
  67831. _this._pointerPressed.push(evt.pointerId);
  67832. if (_this._pointerPressed.length !== 1) {
  67833. return;
  67834. }
  67835. previousPosition = {
  67836. x: evt.clientX,
  67837. y: evt.clientY
  67838. };
  67839. }
  67840. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  67841. if (!noPreventDefault) {
  67842. evt.preventDefault();
  67843. }
  67844. var index = _this._pointerPressed.indexOf(evt.pointerId);
  67845. if (index === -1) {
  67846. return;
  67847. }
  67848. _this._pointerPressed.splice(index, 1);
  67849. if (index != 0) {
  67850. return;
  67851. }
  67852. previousPosition = null;
  67853. _this._offsetX = null;
  67854. _this._offsetY = null;
  67855. }
  67856. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  67857. if (!noPreventDefault) {
  67858. evt.preventDefault();
  67859. }
  67860. if (!previousPosition) {
  67861. return;
  67862. }
  67863. var index = _this._pointerPressed.indexOf(evt.pointerId);
  67864. if (index != 0) {
  67865. return;
  67866. }
  67867. _this._offsetX = evt.clientX - previousPosition.x;
  67868. _this._offsetY = -(evt.clientY - previousPosition.y);
  67869. }
  67870. };
  67871. }
  67872. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  67873. if (this._onLostFocus) {
  67874. element.addEventListener("blur", this._onLostFocus);
  67875. }
  67876. };
  67877. FreeCameraTouchInput.prototype.detachControl = function (element) {
  67878. if (this._pointerInput && element) {
  67879. if (this._observer) {
  67880. this.camera.getScene().onPointerObservable.remove(this._observer);
  67881. this._observer = null;
  67882. }
  67883. if (this._onLostFocus) {
  67884. element.removeEventListener("blur", this._onLostFocus);
  67885. this._onLostFocus = null;
  67886. }
  67887. this._pointerPressed = [];
  67888. this._offsetX = null;
  67889. this._offsetY = null;
  67890. }
  67891. };
  67892. FreeCameraTouchInput.prototype.checkInputs = function () {
  67893. if (this._offsetX && this._offsetY) {
  67894. var camera = this.camera;
  67895. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  67896. if (this._pointerPressed.length > 1) {
  67897. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  67898. }
  67899. else {
  67900. var speed = camera._computeLocalCameraSpeed();
  67901. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  67902. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  67903. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  67904. }
  67905. }
  67906. };
  67907. FreeCameraTouchInput.prototype.getClassName = function () {
  67908. return "FreeCameraTouchInput";
  67909. };
  67910. FreeCameraTouchInput.prototype.getSimpleName = function () {
  67911. return "touch";
  67912. };
  67913. __decorate([
  67914. BABYLON.serialize()
  67915. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  67916. __decorate([
  67917. BABYLON.serialize()
  67918. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  67919. return FreeCameraTouchInput;
  67920. }());
  67921. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  67922. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  67923. })(BABYLON || (BABYLON = {}));
  67924. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  67925. "use strict";
  67926. var BABYLON;
  67927. (function (BABYLON) {
  67928. // We're mainly based on the logic defined into the FreeCamera code
  67929. var TouchCamera = /** @class */ (function (_super) {
  67930. __extends(TouchCamera, _super);
  67931. //-- end properties for backward compatibility for inputs
  67932. function TouchCamera(name, position, scene) {
  67933. var _this = _super.call(this, name, position, scene) || this;
  67934. _this.inputs.addTouch();
  67935. _this._setupInputs();
  67936. return _this;
  67937. }
  67938. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  67939. //-- Begin properties for backward compatibility for inputs
  67940. get: function () {
  67941. var touch = this.inputs.attached["touch"];
  67942. if (touch)
  67943. return touch.touchAngularSensibility;
  67944. return 0;
  67945. },
  67946. set: function (value) {
  67947. var touch = this.inputs.attached["touch"];
  67948. if (touch)
  67949. touch.touchAngularSensibility = value;
  67950. },
  67951. enumerable: true,
  67952. configurable: true
  67953. });
  67954. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  67955. get: function () {
  67956. var touch = this.inputs.attached["touch"];
  67957. if (touch)
  67958. return touch.touchMoveSensibility;
  67959. return 0;
  67960. },
  67961. set: function (value) {
  67962. var touch = this.inputs.attached["touch"];
  67963. if (touch)
  67964. touch.touchMoveSensibility = value;
  67965. },
  67966. enumerable: true,
  67967. configurable: true
  67968. });
  67969. TouchCamera.prototype.getClassName = function () {
  67970. return "TouchCamera";
  67971. };
  67972. TouchCamera.prototype._setupInputs = function () {
  67973. var mouse = this.inputs.attached["mouse"];
  67974. if (mouse) {
  67975. mouse.touchEnabled = false;
  67976. }
  67977. };
  67978. return TouchCamera;
  67979. }(BABYLON.FreeCamera));
  67980. BABYLON.TouchCamera = TouchCamera;
  67981. })(BABYLON || (BABYLON = {}));
  67982. //# sourceMappingURL=babylon.touchCamera.js.map
  67983. "use strict";
  67984. var BABYLON;
  67985. (function (BABYLON) {
  67986. var ProceduralTexture = /** @class */ (function (_super) {
  67987. __extends(ProceduralTexture, _super);
  67988. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  67989. if (fallbackTexture === void 0) { fallbackTexture = null; }
  67990. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67991. if (isCube === void 0) { isCube = false; }
  67992. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67993. _this.isCube = isCube;
  67994. _this.isEnabled = true;
  67995. _this._currentRefreshId = -1;
  67996. _this._refreshRate = 1;
  67997. _this._vertexBuffers = {};
  67998. _this._uniforms = new Array();
  67999. _this._samplers = new Array();
  68000. _this._textures = {};
  68001. _this._floats = {};
  68002. _this._floatsArrays = {};
  68003. _this._colors3 = {};
  68004. _this._colors4 = {};
  68005. _this._vectors2 = {};
  68006. _this._vectors3 = {};
  68007. _this._matrices = {};
  68008. _this._fallbackTextureUsed = false;
  68009. scene.proceduralTextures.push(_this);
  68010. _this._engine = scene.getEngine();
  68011. _this.name = name;
  68012. _this.isRenderTarget = true;
  68013. _this._size = size;
  68014. _this._generateMipMaps = generateMipMaps;
  68015. _this.setFragment(fragment);
  68016. _this._fallbackTexture = fallbackTexture;
  68017. if (isCube) {
  68018. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  68019. _this.setFloat("face", 0);
  68020. }
  68021. else {
  68022. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  68023. }
  68024. // VBO
  68025. var vertices = [];
  68026. vertices.push(1, 1);
  68027. vertices.push(-1, 1);
  68028. vertices.push(-1, -1);
  68029. vertices.push(1, -1);
  68030. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68031. _this._createIndexBuffer();
  68032. return _this;
  68033. }
  68034. ProceduralTexture.prototype._createIndexBuffer = function () {
  68035. var engine = this._engine;
  68036. // Indices
  68037. var indices = [];
  68038. indices.push(0);
  68039. indices.push(1);
  68040. indices.push(2);
  68041. indices.push(0);
  68042. indices.push(2);
  68043. indices.push(3);
  68044. this._indexBuffer = engine.createIndexBuffer(indices);
  68045. };
  68046. ProceduralTexture.prototype._rebuild = function () {
  68047. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68048. if (vb) {
  68049. vb._rebuild();
  68050. }
  68051. this._createIndexBuffer();
  68052. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68053. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68054. }
  68055. };
  68056. ProceduralTexture.prototype.reset = function () {
  68057. if (this._effect === undefined) {
  68058. return;
  68059. }
  68060. var engine = this._engine;
  68061. engine._releaseEffect(this._effect);
  68062. };
  68063. ProceduralTexture.prototype.isReady = function () {
  68064. var _this = this;
  68065. var engine = this._engine;
  68066. var shaders;
  68067. if (!this._fragment) {
  68068. return false;
  68069. }
  68070. if (this._fallbackTextureUsed) {
  68071. return true;
  68072. }
  68073. if (this._fragment.fragmentElement !== undefined) {
  68074. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  68075. }
  68076. else {
  68077. shaders = { vertex: "procedural", fragment: this._fragment };
  68078. }
  68079. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  68080. _this.releaseInternalTexture();
  68081. if (_this._fallbackTexture) {
  68082. _this._texture = _this._fallbackTexture._texture;
  68083. if (_this._texture) {
  68084. _this._texture.incrementReferences();
  68085. }
  68086. }
  68087. _this._fallbackTextureUsed = true;
  68088. });
  68089. return this._effect.isReady();
  68090. };
  68091. ProceduralTexture.prototype.resetRefreshCounter = function () {
  68092. this._currentRefreshId = -1;
  68093. };
  68094. ProceduralTexture.prototype.setFragment = function (fragment) {
  68095. this._fragment = fragment;
  68096. };
  68097. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  68098. get: function () {
  68099. return this._refreshRate;
  68100. },
  68101. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  68102. set: function (value) {
  68103. this._refreshRate = value;
  68104. this.resetRefreshCounter();
  68105. },
  68106. enumerable: true,
  68107. configurable: true
  68108. });
  68109. ProceduralTexture.prototype._shouldRender = function () {
  68110. if (!this.isEnabled || !this.isReady() || !this._texture) {
  68111. return false;
  68112. }
  68113. if (this._fallbackTextureUsed) {
  68114. return false;
  68115. }
  68116. if (this._currentRefreshId === -1) {
  68117. this._currentRefreshId = 1;
  68118. return true;
  68119. }
  68120. if (this.refreshRate === this._currentRefreshId) {
  68121. this._currentRefreshId = 1;
  68122. return true;
  68123. }
  68124. this._currentRefreshId++;
  68125. return false;
  68126. };
  68127. ProceduralTexture.prototype.getRenderSize = function () {
  68128. return this._size;
  68129. };
  68130. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  68131. if (this._fallbackTextureUsed) {
  68132. return;
  68133. }
  68134. this.releaseInternalTexture();
  68135. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  68136. };
  68137. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  68138. if (this._uniforms.indexOf(uniformName) === -1) {
  68139. this._uniforms.push(uniformName);
  68140. }
  68141. };
  68142. ProceduralTexture.prototype.setTexture = function (name, texture) {
  68143. if (this._samplers.indexOf(name) === -1) {
  68144. this._samplers.push(name);
  68145. }
  68146. this._textures[name] = texture;
  68147. return this;
  68148. };
  68149. ProceduralTexture.prototype.setFloat = function (name, value) {
  68150. this._checkUniform(name);
  68151. this._floats[name] = value;
  68152. return this;
  68153. };
  68154. ProceduralTexture.prototype.setFloats = function (name, value) {
  68155. this._checkUniform(name);
  68156. this._floatsArrays[name] = value;
  68157. return this;
  68158. };
  68159. ProceduralTexture.prototype.setColor3 = function (name, value) {
  68160. this._checkUniform(name);
  68161. this._colors3[name] = value;
  68162. return this;
  68163. };
  68164. ProceduralTexture.prototype.setColor4 = function (name, value) {
  68165. this._checkUniform(name);
  68166. this._colors4[name] = value;
  68167. return this;
  68168. };
  68169. ProceduralTexture.prototype.setVector2 = function (name, value) {
  68170. this._checkUniform(name);
  68171. this._vectors2[name] = value;
  68172. return this;
  68173. };
  68174. ProceduralTexture.prototype.setVector3 = function (name, value) {
  68175. this._checkUniform(name);
  68176. this._vectors3[name] = value;
  68177. return this;
  68178. };
  68179. ProceduralTexture.prototype.setMatrix = function (name, value) {
  68180. this._checkUniform(name);
  68181. this._matrices[name] = value;
  68182. return this;
  68183. };
  68184. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  68185. var scene = this.getScene();
  68186. if (!scene) {
  68187. return;
  68188. }
  68189. var engine = this._engine;
  68190. // Render
  68191. engine.enableEffect(this._effect);
  68192. engine.setState(false);
  68193. // Texture
  68194. for (var name in this._textures) {
  68195. this._effect.setTexture(name, this._textures[name]);
  68196. }
  68197. // Float
  68198. for (name in this._floats) {
  68199. this._effect.setFloat(name, this._floats[name]);
  68200. }
  68201. // Floats
  68202. for (name in this._floatsArrays) {
  68203. this._effect.setArray(name, this._floatsArrays[name]);
  68204. }
  68205. // Color3
  68206. for (name in this._colors3) {
  68207. this._effect.setColor3(name, this._colors3[name]);
  68208. }
  68209. // Color4
  68210. for (name in this._colors4) {
  68211. var color = this._colors4[name];
  68212. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  68213. }
  68214. // Vector2
  68215. for (name in this._vectors2) {
  68216. this._effect.setVector2(name, this._vectors2[name]);
  68217. }
  68218. // Vector3
  68219. for (name in this._vectors3) {
  68220. this._effect.setVector3(name, this._vectors3[name]);
  68221. }
  68222. // Matrix
  68223. for (name in this._matrices) {
  68224. this._effect.setMatrix(name, this._matrices[name]);
  68225. }
  68226. if (!this._texture) {
  68227. return;
  68228. }
  68229. if (this.isCube) {
  68230. for (var face = 0; face < 6; face++) {
  68231. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  68232. // VBOs
  68233. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  68234. this._effect.setFloat("face", face);
  68235. // Clear
  68236. engine.clear(scene.clearColor, true, true, true);
  68237. // Draw order
  68238. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68239. // Mipmaps
  68240. if (face === 5) {
  68241. engine.generateMipMapsForCubemap(this._texture);
  68242. }
  68243. }
  68244. }
  68245. else {
  68246. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  68247. // VBOs
  68248. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  68249. // Clear
  68250. engine.clear(scene.clearColor, true, true, true);
  68251. // Draw order
  68252. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68253. }
  68254. // Unbind
  68255. engine.unBindFramebuffer(this._texture, this.isCube);
  68256. if (this.onGenerated) {
  68257. this.onGenerated();
  68258. }
  68259. };
  68260. ProceduralTexture.prototype.clone = function () {
  68261. var textureSize = this.getSize();
  68262. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  68263. // Base texture
  68264. newTexture.hasAlpha = this.hasAlpha;
  68265. newTexture.level = this.level;
  68266. // RenderTarget Texture
  68267. newTexture.coordinatesMode = this.coordinatesMode;
  68268. return newTexture;
  68269. };
  68270. ProceduralTexture.prototype.dispose = function () {
  68271. var scene = this.getScene();
  68272. if (!scene) {
  68273. return;
  68274. }
  68275. var index = scene.proceduralTextures.indexOf(this);
  68276. if (index >= 0) {
  68277. scene.proceduralTextures.splice(index, 1);
  68278. }
  68279. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68280. if (vertexBuffer) {
  68281. vertexBuffer.dispose();
  68282. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68283. }
  68284. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  68285. this._indexBuffer = null;
  68286. }
  68287. _super.prototype.dispose.call(this);
  68288. };
  68289. return ProceduralTexture;
  68290. }(BABYLON.Texture));
  68291. BABYLON.ProceduralTexture = ProceduralTexture;
  68292. })(BABYLON || (BABYLON = {}));
  68293. //# sourceMappingURL=babylon.proceduralTexture.js.map
  68294. "use strict";
  68295. var BABYLON;
  68296. (function (BABYLON) {
  68297. var CustomProceduralTexture = /** @class */ (function (_super) {
  68298. __extends(CustomProceduralTexture, _super);
  68299. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  68300. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  68301. _this._animate = true;
  68302. _this._time = 0;
  68303. _this._texturePath = texturePath;
  68304. //Try to load json
  68305. _this.loadJson(texturePath);
  68306. _this.refreshRate = 1;
  68307. return _this;
  68308. }
  68309. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  68310. var _this = this;
  68311. var noConfigFile = function () {
  68312. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  68313. try {
  68314. _this.setFragment(_this._texturePath);
  68315. }
  68316. catch (ex) {
  68317. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  68318. }
  68319. };
  68320. var configFileUrl = jsonUrl + "/config.json";
  68321. var xhr = new XMLHttpRequest();
  68322. xhr.open("GET", configFileUrl, true);
  68323. xhr.addEventListener("load", function () {
  68324. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68325. try {
  68326. _this._config = JSON.parse(xhr.response);
  68327. _this.updateShaderUniforms();
  68328. _this.updateTextures();
  68329. _this.setFragment(_this._texturePath + "/custom");
  68330. _this._animate = _this._config.animate;
  68331. _this.refreshRate = _this._config.refreshrate;
  68332. }
  68333. catch (ex) {
  68334. noConfigFile();
  68335. }
  68336. }
  68337. else {
  68338. noConfigFile();
  68339. }
  68340. }, false);
  68341. xhr.addEventListener("error", function () {
  68342. noConfigFile();
  68343. }, false);
  68344. try {
  68345. xhr.send();
  68346. }
  68347. catch (ex) {
  68348. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  68349. }
  68350. };
  68351. CustomProceduralTexture.prototype.isReady = function () {
  68352. if (!_super.prototype.isReady.call(this)) {
  68353. return false;
  68354. }
  68355. for (var name in this._textures) {
  68356. var texture = this._textures[name];
  68357. if (!texture.isReady()) {
  68358. return false;
  68359. }
  68360. }
  68361. return true;
  68362. };
  68363. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  68364. var scene = this.getScene();
  68365. if (this._animate && scene) {
  68366. this._time += scene.getAnimationRatio() * 0.03;
  68367. this.updateShaderUniforms();
  68368. }
  68369. _super.prototype.render.call(this, useCameraPostProcess);
  68370. };
  68371. CustomProceduralTexture.prototype.updateTextures = function () {
  68372. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  68373. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  68374. }
  68375. };
  68376. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  68377. if (this._config) {
  68378. for (var j = 0; j < this._config.uniforms.length; j++) {
  68379. var uniform = this._config.uniforms[j];
  68380. switch (uniform.type) {
  68381. case "float":
  68382. this.setFloat(uniform.name, uniform.value);
  68383. break;
  68384. case "color3":
  68385. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  68386. break;
  68387. case "color4":
  68388. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  68389. break;
  68390. case "vector2":
  68391. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  68392. break;
  68393. case "vector3":
  68394. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  68395. break;
  68396. }
  68397. }
  68398. }
  68399. this.setFloat("time", this._time);
  68400. };
  68401. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  68402. get: function () {
  68403. return this._animate;
  68404. },
  68405. set: function (value) {
  68406. this._animate = value;
  68407. },
  68408. enumerable: true,
  68409. configurable: true
  68410. });
  68411. return CustomProceduralTexture;
  68412. }(BABYLON.ProceduralTexture));
  68413. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  68414. })(BABYLON || (BABYLON = {}));
  68415. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  68416. "use strict";
  68417. var BABYLON;
  68418. (function (BABYLON) {
  68419. var FreeCameraGamepadInput = /** @class */ (function () {
  68420. function FreeCameraGamepadInput() {
  68421. this.gamepadAngularSensibility = 200;
  68422. this.gamepadMoveSensibility = 40;
  68423. // private members
  68424. this._cameraTransform = BABYLON.Matrix.Identity();
  68425. this._deltaTransform = BABYLON.Vector3.Zero();
  68426. this._vector3 = BABYLON.Vector3.Zero();
  68427. this._vector2 = BABYLON.Vector2.Zero();
  68428. }
  68429. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  68430. var _this = this;
  68431. var manager = this.camera.getScene().gamepadManager;
  68432. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68433. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  68434. // prioritize XBOX gamepads.
  68435. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68436. _this.gamepad = gamepad;
  68437. }
  68438. }
  68439. });
  68440. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68441. if (_this.gamepad === gamepad) {
  68442. _this.gamepad = null;
  68443. }
  68444. });
  68445. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68446. };
  68447. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  68448. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68449. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68450. this.gamepad = null;
  68451. };
  68452. FreeCameraGamepadInput.prototype.checkInputs = function () {
  68453. if (this.gamepad && this.gamepad.leftStick) {
  68454. var camera = this.camera;
  68455. var LSValues = this.gamepad.leftStick;
  68456. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  68457. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68458. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  68459. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  68460. var RSValues = this.gamepad.rightStick;
  68461. if (RSValues) {
  68462. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  68463. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  68464. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  68465. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  68466. }
  68467. else {
  68468. RSValues = { x: 0, y: 0 };
  68469. }
  68470. if (!camera.rotationQuaternion) {
  68471. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  68472. }
  68473. else {
  68474. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  68475. }
  68476. var speed = camera._computeLocalCameraSpeed() * 50.0;
  68477. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  68478. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  68479. camera.cameraDirection.addInPlace(this._deltaTransform);
  68480. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  68481. camera.cameraRotation.addInPlace(this._vector2);
  68482. }
  68483. };
  68484. FreeCameraGamepadInput.prototype.getClassName = function () {
  68485. return "FreeCameraGamepadInput";
  68486. };
  68487. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  68488. return "gamepad";
  68489. };
  68490. __decorate([
  68491. BABYLON.serialize()
  68492. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  68493. __decorate([
  68494. BABYLON.serialize()
  68495. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68496. return FreeCameraGamepadInput;
  68497. }());
  68498. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  68499. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  68500. })(BABYLON || (BABYLON = {}));
  68501. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  68502. "use strict";
  68503. var BABYLON;
  68504. (function (BABYLON) {
  68505. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  68506. function ArcRotateCameraGamepadInput() {
  68507. this.gamepadRotationSensibility = 80;
  68508. this.gamepadMoveSensibility = 40;
  68509. }
  68510. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  68511. var _this = this;
  68512. var manager = this.camera.getScene().gamepadManager;
  68513. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68514. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  68515. // prioritize XBOX gamepads.
  68516. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68517. _this.gamepad = gamepad;
  68518. }
  68519. }
  68520. });
  68521. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68522. if (_this.gamepad === gamepad) {
  68523. _this.gamepad = null;
  68524. }
  68525. });
  68526. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68527. };
  68528. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  68529. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68530. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68531. this.gamepad = null;
  68532. };
  68533. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  68534. if (this.gamepad) {
  68535. var camera = this.camera;
  68536. var RSValues = this.gamepad.rightStick;
  68537. if (RSValues) {
  68538. if (RSValues.x != 0) {
  68539. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  68540. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  68541. camera.inertialAlphaOffset += normalizedRX;
  68542. }
  68543. }
  68544. if (RSValues.y != 0) {
  68545. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  68546. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  68547. camera.inertialBetaOffset += normalizedRY;
  68548. }
  68549. }
  68550. }
  68551. var LSValues = this.gamepad.leftStick;
  68552. if (LSValues && LSValues.y != 0) {
  68553. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68554. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  68555. this.camera.inertialRadiusOffset -= normalizedLY;
  68556. }
  68557. }
  68558. }
  68559. };
  68560. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  68561. return "ArcRotateCameraGamepadInput";
  68562. };
  68563. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  68564. return "gamepad";
  68565. };
  68566. __decorate([
  68567. BABYLON.serialize()
  68568. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  68569. __decorate([
  68570. BABYLON.serialize()
  68571. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68572. return ArcRotateCameraGamepadInput;
  68573. }());
  68574. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  68575. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  68576. })(BABYLON || (BABYLON = {}));
  68577. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  68578. "use strict";
  68579. var BABYLON;
  68580. (function (BABYLON) {
  68581. var GamepadManager = /** @class */ (function () {
  68582. function GamepadManager(_scene) {
  68583. var _this = this;
  68584. this._scene = _scene;
  68585. this._babylonGamepads = [];
  68586. this._oneGamepadConnected = false;
  68587. this._isMonitoring = false;
  68588. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  68589. if (!BABYLON.Tools.IsWindowObjectExist()) {
  68590. this._gamepadEventSupported = false;
  68591. }
  68592. else {
  68593. this._gamepadEventSupported = 'GamepadEvent' in window;
  68594. this._gamepadSupport = (navigator.getGamepads ||
  68595. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  68596. }
  68597. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  68598. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  68599. for (var i in _this._babylonGamepads) {
  68600. var gamepad = _this._babylonGamepads[i];
  68601. if (gamepad && gamepad._isConnected) {
  68602. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  68603. }
  68604. }
  68605. });
  68606. this._onGamepadConnectedEvent = function (evt) {
  68607. var gamepad = evt.gamepad;
  68608. if (gamepad.index in _this._babylonGamepads) {
  68609. if (_this._babylonGamepads[gamepad.index].isConnected) {
  68610. return;
  68611. }
  68612. }
  68613. var newGamepad;
  68614. if (_this._babylonGamepads[gamepad.index]) {
  68615. newGamepad = _this._babylonGamepads[gamepad.index];
  68616. newGamepad.browserGamepad = gamepad;
  68617. newGamepad._isConnected = true;
  68618. }
  68619. else {
  68620. newGamepad = _this._addNewGamepad(gamepad);
  68621. }
  68622. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68623. _this._startMonitoringGamepads();
  68624. };
  68625. this._onGamepadDisconnectedEvent = function (evt) {
  68626. var gamepad = evt.gamepad;
  68627. // Remove the gamepad from the list of gamepads to monitor.
  68628. for (var i in _this._babylonGamepads) {
  68629. if (_this._babylonGamepads[i].index === gamepad.index) {
  68630. var disconnectedGamepad = _this._babylonGamepads[i];
  68631. disconnectedGamepad._isConnected = false;
  68632. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  68633. break;
  68634. }
  68635. }
  68636. };
  68637. if (this._gamepadSupport) {
  68638. //first add already-connected gamepads
  68639. this._updateGamepadObjects();
  68640. if (this._babylonGamepads.length) {
  68641. this._startMonitoringGamepads();
  68642. }
  68643. // Checking if the gamepad connected event is supported (like in Firefox)
  68644. if (this._gamepadEventSupported) {
  68645. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  68646. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  68647. }
  68648. else {
  68649. this._startMonitoringGamepads();
  68650. }
  68651. }
  68652. }
  68653. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  68654. get: function () {
  68655. return this._babylonGamepads;
  68656. },
  68657. enumerable: true,
  68658. configurable: true
  68659. });
  68660. GamepadManager.prototype.getGamepadByType = function (type) {
  68661. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  68662. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  68663. var gamepad = _a[_i];
  68664. if (gamepad && gamepad.type === type) {
  68665. return gamepad;
  68666. }
  68667. }
  68668. return null;
  68669. };
  68670. GamepadManager.prototype.dispose = function () {
  68671. if (this._gamepadEventSupported) {
  68672. if (this._onGamepadConnectedEvent) {
  68673. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  68674. }
  68675. if (this._onGamepadDisconnectedEvent) {
  68676. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  68677. }
  68678. this._onGamepadConnectedEvent = null;
  68679. this._onGamepadDisconnectedEvent = null;
  68680. }
  68681. this._babylonGamepads.forEach(function (gamepad) {
  68682. gamepad.dispose();
  68683. });
  68684. this.onGamepadConnectedObservable.clear();
  68685. this.onGamepadDisconnectedObservable.clear();
  68686. this._oneGamepadConnected = false;
  68687. this._stopMonitoringGamepads();
  68688. this._babylonGamepads = [];
  68689. };
  68690. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  68691. if (!this._oneGamepadConnected) {
  68692. this._oneGamepadConnected = true;
  68693. }
  68694. var newGamepad;
  68695. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  68696. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  68697. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  68698. }
  68699. else if (gamepad.pose) {
  68700. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  68701. }
  68702. else {
  68703. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  68704. }
  68705. this._babylonGamepads[newGamepad.index] = newGamepad;
  68706. return newGamepad;
  68707. };
  68708. GamepadManager.prototype._startMonitoringGamepads = function () {
  68709. if (!this._isMonitoring) {
  68710. this._isMonitoring = true;
  68711. //back-comp
  68712. if (!this._scene) {
  68713. this._checkGamepadsStatus();
  68714. }
  68715. }
  68716. };
  68717. GamepadManager.prototype._stopMonitoringGamepads = function () {
  68718. this._isMonitoring = false;
  68719. };
  68720. GamepadManager.prototype._checkGamepadsStatus = function () {
  68721. var _this = this;
  68722. // Hack to be compatible Chrome
  68723. this._updateGamepadObjects();
  68724. for (var i in this._babylonGamepads) {
  68725. var gamepad = this._babylonGamepads[i];
  68726. if (!gamepad || !gamepad.isConnected) {
  68727. continue;
  68728. }
  68729. gamepad.update();
  68730. }
  68731. if (this._isMonitoring && !this._scene) {
  68732. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  68733. }
  68734. };
  68735. // This function is called only on Chrome, which does not properly support
  68736. // connection/disconnection events and forces you to recopy again the gamepad object
  68737. GamepadManager.prototype._updateGamepadObjects = function () {
  68738. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  68739. for (var i = 0; i < gamepads.length; i++) {
  68740. if (gamepads[i]) {
  68741. if (!this._babylonGamepads[gamepads[i].index]) {
  68742. var newGamepad = this._addNewGamepad(gamepads[i]);
  68743. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68744. }
  68745. else {
  68746. // Forced to copy again this object for Chrome for unknown reason
  68747. this._babylonGamepads[i].browserGamepad = gamepads[i];
  68748. if (!this._babylonGamepads[i].isConnected) {
  68749. this._babylonGamepads[i]._isConnected = true;
  68750. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  68751. }
  68752. }
  68753. }
  68754. }
  68755. };
  68756. return GamepadManager;
  68757. }());
  68758. BABYLON.GamepadManager = GamepadManager;
  68759. })(BABYLON || (BABYLON = {}));
  68760. //# sourceMappingURL=babylon.gamepadManager.js.map
  68761. "use strict";
  68762. var BABYLON;
  68763. (function (BABYLON) {
  68764. var StickValues = /** @class */ (function () {
  68765. function StickValues(x, y) {
  68766. this.x = x;
  68767. this.y = y;
  68768. }
  68769. return StickValues;
  68770. }());
  68771. BABYLON.StickValues = StickValues;
  68772. var Gamepad = /** @class */ (function () {
  68773. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  68774. if (leftStickX === void 0) { leftStickX = 0; }
  68775. if (leftStickY === void 0) { leftStickY = 1; }
  68776. if (rightStickX === void 0) { rightStickX = 2; }
  68777. if (rightStickY === void 0) { rightStickY = 3; }
  68778. this.id = id;
  68779. this.index = index;
  68780. this.browserGamepad = browserGamepad;
  68781. this._isConnected = true;
  68782. this._invertLeftStickY = false;
  68783. this.type = Gamepad.GAMEPAD;
  68784. this._leftStickAxisX = leftStickX;
  68785. this._leftStickAxisY = leftStickY;
  68786. this._rightStickAxisX = rightStickX;
  68787. this._rightStickAxisY = rightStickY;
  68788. if (this.browserGamepad.axes.length >= 2) {
  68789. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  68790. }
  68791. if (this.browserGamepad.axes.length >= 4) {
  68792. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  68793. }
  68794. }
  68795. Object.defineProperty(Gamepad.prototype, "isConnected", {
  68796. get: function () {
  68797. return this._isConnected;
  68798. },
  68799. enumerable: true,
  68800. configurable: true
  68801. });
  68802. Gamepad.prototype.onleftstickchanged = function (callback) {
  68803. this._onleftstickchanged = callback;
  68804. };
  68805. Gamepad.prototype.onrightstickchanged = function (callback) {
  68806. this._onrightstickchanged = callback;
  68807. };
  68808. Object.defineProperty(Gamepad.prototype, "leftStick", {
  68809. get: function () {
  68810. return this._leftStick;
  68811. },
  68812. set: function (newValues) {
  68813. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  68814. this._onleftstickchanged(newValues);
  68815. }
  68816. this._leftStick = newValues;
  68817. },
  68818. enumerable: true,
  68819. configurable: true
  68820. });
  68821. Object.defineProperty(Gamepad.prototype, "rightStick", {
  68822. get: function () {
  68823. return this._rightStick;
  68824. },
  68825. set: function (newValues) {
  68826. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  68827. this._onrightstickchanged(newValues);
  68828. }
  68829. this._rightStick = newValues;
  68830. },
  68831. enumerable: true,
  68832. configurable: true
  68833. });
  68834. Gamepad.prototype.update = function () {
  68835. if (this._leftStick) {
  68836. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  68837. if (this._invertLeftStickY) {
  68838. this.leftStick.y *= -1;
  68839. }
  68840. }
  68841. if (this._rightStick) {
  68842. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  68843. }
  68844. };
  68845. Gamepad.prototype.dispose = function () {
  68846. };
  68847. Gamepad.GAMEPAD = 0;
  68848. Gamepad.GENERIC = 1;
  68849. Gamepad.XBOX = 2;
  68850. Gamepad.POSE_ENABLED = 3;
  68851. return Gamepad;
  68852. }());
  68853. BABYLON.Gamepad = Gamepad;
  68854. var GenericPad = /** @class */ (function (_super) {
  68855. __extends(GenericPad, _super);
  68856. function GenericPad(id, index, browserGamepad) {
  68857. var _this = _super.call(this, id, index, browserGamepad) || this;
  68858. _this.onButtonDownObservable = new BABYLON.Observable();
  68859. _this.onButtonUpObservable = new BABYLON.Observable();
  68860. _this.type = Gamepad.GENERIC;
  68861. _this._buttons = new Array(browserGamepad.buttons.length);
  68862. return _this;
  68863. }
  68864. GenericPad.prototype.onbuttondown = function (callback) {
  68865. this._onbuttondown = callback;
  68866. };
  68867. GenericPad.prototype.onbuttonup = function (callback) {
  68868. this._onbuttonup = callback;
  68869. };
  68870. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  68871. if (newValue !== currentValue) {
  68872. if (newValue === 1) {
  68873. if (this._onbuttondown) {
  68874. this._onbuttondown(buttonIndex);
  68875. }
  68876. this.onButtonDownObservable.notifyObservers(buttonIndex);
  68877. }
  68878. if (newValue === 0) {
  68879. if (this._onbuttonup) {
  68880. this._onbuttonup(buttonIndex);
  68881. }
  68882. this.onButtonUpObservable.notifyObservers(buttonIndex);
  68883. }
  68884. }
  68885. return newValue;
  68886. };
  68887. GenericPad.prototype.update = function () {
  68888. _super.prototype.update.call(this);
  68889. for (var index = 0; index < this._buttons.length; index++) {
  68890. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  68891. }
  68892. };
  68893. GenericPad.prototype.dispose = function () {
  68894. _super.prototype.dispose.call(this);
  68895. this.onButtonDownObservable.clear();
  68896. this.onButtonUpObservable.clear();
  68897. };
  68898. return GenericPad;
  68899. }(Gamepad));
  68900. BABYLON.GenericPad = GenericPad;
  68901. })(BABYLON || (BABYLON = {}));
  68902. //# sourceMappingURL=babylon.gamepad.js.map
  68903. "use strict";
  68904. var BABYLON;
  68905. (function (BABYLON) {
  68906. var Xbox360Button;
  68907. (function (Xbox360Button) {
  68908. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  68909. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  68910. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  68911. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  68912. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  68913. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  68914. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  68915. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  68916. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  68917. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  68918. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  68919. var Xbox360Dpad;
  68920. (function (Xbox360Dpad) {
  68921. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  68922. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  68923. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  68924. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  68925. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  68926. var Xbox360Pad = /** @class */ (function (_super) {
  68927. __extends(Xbox360Pad, _super);
  68928. function Xbox360Pad(id, index, gamepad, xboxOne) {
  68929. if (xboxOne === void 0) { xboxOne = false; }
  68930. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  68931. _this._leftTrigger = 0;
  68932. _this._rightTrigger = 0;
  68933. _this.onButtonDownObservable = new BABYLON.Observable();
  68934. _this.onButtonUpObservable = new BABYLON.Observable();
  68935. _this.onPadDownObservable = new BABYLON.Observable();
  68936. _this.onPadUpObservable = new BABYLON.Observable();
  68937. _this._buttonA = 0;
  68938. _this._buttonB = 0;
  68939. _this._buttonX = 0;
  68940. _this._buttonY = 0;
  68941. _this._buttonBack = 0;
  68942. _this._buttonStart = 0;
  68943. _this._buttonLB = 0;
  68944. _this._buttonRB = 0;
  68945. _this._buttonLeftStick = 0;
  68946. _this._buttonRightStick = 0;
  68947. _this._dPadUp = 0;
  68948. _this._dPadDown = 0;
  68949. _this._dPadLeft = 0;
  68950. _this._dPadRight = 0;
  68951. _this._isXboxOnePad = false;
  68952. _this.type = BABYLON.Gamepad.XBOX;
  68953. _this._isXboxOnePad = xboxOne;
  68954. return _this;
  68955. }
  68956. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  68957. this._onlefttriggerchanged = callback;
  68958. };
  68959. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  68960. this._onrighttriggerchanged = callback;
  68961. };
  68962. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  68963. get: function () {
  68964. return this._leftTrigger;
  68965. },
  68966. set: function (newValue) {
  68967. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  68968. this._onlefttriggerchanged(newValue);
  68969. }
  68970. this._leftTrigger = newValue;
  68971. },
  68972. enumerable: true,
  68973. configurable: true
  68974. });
  68975. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  68976. get: function () {
  68977. return this._rightTrigger;
  68978. },
  68979. set: function (newValue) {
  68980. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  68981. this._onrighttriggerchanged(newValue);
  68982. }
  68983. this._rightTrigger = newValue;
  68984. },
  68985. enumerable: true,
  68986. configurable: true
  68987. });
  68988. Xbox360Pad.prototype.onbuttondown = function (callback) {
  68989. this._onbuttondown = callback;
  68990. };
  68991. Xbox360Pad.prototype.onbuttonup = function (callback) {
  68992. this._onbuttonup = callback;
  68993. };
  68994. Xbox360Pad.prototype.ondpaddown = function (callback) {
  68995. this._ondpaddown = callback;
  68996. };
  68997. Xbox360Pad.prototype.ondpadup = function (callback) {
  68998. this._ondpadup = callback;
  68999. };
  69000. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  69001. if (newValue !== currentValue) {
  69002. if (newValue === 1) {
  69003. if (this._onbuttondown) {
  69004. this._onbuttondown(buttonType);
  69005. }
  69006. this.onButtonDownObservable.notifyObservers(buttonType);
  69007. }
  69008. if (newValue === 0) {
  69009. if (this._onbuttonup) {
  69010. this._onbuttonup(buttonType);
  69011. }
  69012. this.onButtonUpObservable.notifyObservers(buttonType);
  69013. }
  69014. }
  69015. return newValue;
  69016. };
  69017. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  69018. if (newValue !== currentValue) {
  69019. if (newValue === 1) {
  69020. if (this._ondpaddown) {
  69021. this._ondpaddown(buttonType);
  69022. }
  69023. this.onPadDownObservable.notifyObservers(buttonType);
  69024. }
  69025. if (newValue === 0) {
  69026. if (this._ondpadup) {
  69027. this._ondpadup(buttonType);
  69028. }
  69029. this.onPadUpObservable.notifyObservers(buttonType);
  69030. }
  69031. }
  69032. return newValue;
  69033. };
  69034. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  69035. get: function () {
  69036. return this._buttonA;
  69037. },
  69038. set: function (value) {
  69039. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  69040. },
  69041. enumerable: true,
  69042. configurable: true
  69043. });
  69044. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  69045. get: function () {
  69046. return this._buttonB;
  69047. },
  69048. set: function (value) {
  69049. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  69050. },
  69051. enumerable: true,
  69052. configurable: true
  69053. });
  69054. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  69055. get: function () {
  69056. return this._buttonX;
  69057. },
  69058. set: function (value) {
  69059. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  69060. },
  69061. enumerable: true,
  69062. configurable: true
  69063. });
  69064. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  69065. get: function () {
  69066. return this._buttonY;
  69067. },
  69068. set: function (value) {
  69069. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  69070. },
  69071. enumerable: true,
  69072. configurable: true
  69073. });
  69074. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  69075. get: function () {
  69076. return this._buttonStart;
  69077. },
  69078. set: function (value) {
  69079. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  69080. },
  69081. enumerable: true,
  69082. configurable: true
  69083. });
  69084. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  69085. get: function () {
  69086. return this._buttonBack;
  69087. },
  69088. set: function (value) {
  69089. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  69090. },
  69091. enumerable: true,
  69092. configurable: true
  69093. });
  69094. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  69095. get: function () {
  69096. return this._buttonLB;
  69097. },
  69098. set: function (value) {
  69099. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  69100. },
  69101. enumerable: true,
  69102. configurable: true
  69103. });
  69104. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  69105. get: function () {
  69106. return this._buttonRB;
  69107. },
  69108. set: function (value) {
  69109. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  69110. },
  69111. enumerable: true,
  69112. configurable: true
  69113. });
  69114. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  69115. get: function () {
  69116. return this._buttonLeftStick;
  69117. },
  69118. set: function (value) {
  69119. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  69120. },
  69121. enumerable: true,
  69122. configurable: true
  69123. });
  69124. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  69125. get: function () {
  69126. return this._buttonRightStick;
  69127. },
  69128. set: function (value) {
  69129. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  69130. },
  69131. enumerable: true,
  69132. configurable: true
  69133. });
  69134. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  69135. get: function () {
  69136. return this._dPadUp;
  69137. },
  69138. set: function (value) {
  69139. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  69140. },
  69141. enumerable: true,
  69142. configurable: true
  69143. });
  69144. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  69145. get: function () {
  69146. return this._dPadDown;
  69147. },
  69148. set: function (value) {
  69149. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  69150. },
  69151. enumerable: true,
  69152. configurable: true
  69153. });
  69154. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  69155. get: function () {
  69156. return this._dPadLeft;
  69157. },
  69158. set: function (value) {
  69159. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  69160. },
  69161. enumerable: true,
  69162. configurable: true
  69163. });
  69164. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  69165. get: function () {
  69166. return this._dPadRight;
  69167. },
  69168. set: function (value) {
  69169. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  69170. },
  69171. enumerable: true,
  69172. configurable: true
  69173. });
  69174. Xbox360Pad.prototype.update = function () {
  69175. _super.prototype.update.call(this);
  69176. if (this._isXboxOnePad) {
  69177. this.buttonA = this.browserGamepad.buttons[0].value;
  69178. this.buttonB = this.browserGamepad.buttons[1].value;
  69179. this.buttonX = this.browserGamepad.buttons[2].value;
  69180. this.buttonY = this.browserGamepad.buttons[3].value;
  69181. this.buttonLB = this.browserGamepad.buttons[4].value;
  69182. this.buttonRB = this.browserGamepad.buttons[5].value;
  69183. this.leftTrigger = this.browserGamepad.axes[2];
  69184. this.rightTrigger = this.browserGamepad.axes[5];
  69185. this.buttonBack = this.browserGamepad.buttons[9].value;
  69186. this.buttonStart = this.browserGamepad.buttons[8].value;
  69187. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  69188. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  69189. this.dPadUp = this.browserGamepad.buttons[11].value;
  69190. this.dPadDown = this.browserGamepad.buttons[12].value;
  69191. this.dPadLeft = this.browserGamepad.buttons[13].value;
  69192. this.dPadRight = this.browserGamepad.buttons[14].value;
  69193. }
  69194. else {
  69195. this.buttonA = this.browserGamepad.buttons[0].value;
  69196. this.buttonB = this.browserGamepad.buttons[1].value;
  69197. this.buttonX = this.browserGamepad.buttons[2].value;
  69198. this.buttonY = this.browserGamepad.buttons[3].value;
  69199. this.buttonLB = this.browserGamepad.buttons[4].value;
  69200. this.buttonRB = this.browserGamepad.buttons[5].value;
  69201. this.leftTrigger = this.browserGamepad.buttons[6].value;
  69202. this.rightTrigger = this.browserGamepad.buttons[7].value;
  69203. this.buttonBack = this.browserGamepad.buttons[8].value;
  69204. this.buttonStart = this.browserGamepad.buttons[9].value;
  69205. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  69206. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  69207. this.dPadUp = this.browserGamepad.buttons[12].value;
  69208. this.dPadDown = this.browserGamepad.buttons[13].value;
  69209. this.dPadLeft = this.browserGamepad.buttons[14].value;
  69210. this.dPadRight = this.browserGamepad.buttons[15].value;
  69211. }
  69212. };
  69213. Xbox360Pad.prototype.dispose = function () {
  69214. _super.prototype.dispose.call(this);
  69215. this.onButtonDownObservable.clear();
  69216. this.onButtonUpObservable.clear();
  69217. this.onPadDownObservable.clear();
  69218. this.onPadUpObservable.clear();
  69219. };
  69220. return Xbox360Pad;
  69221. }(BABYLON.Gamepad));
  69222. BABYLON.Xbox360Pad = Xbox360Pad;
  69223. })(BABYLON || (BABYLON = {}));
  69224. //# sourceMappingURL=babylon.xboxGamepad.js.map
  69225. "use strict";
  69226. var BABYLON;
  69227. (function (BABYLON) {
  69228. /**
  69229. * Defines the types of pose enabled controllers that are supported
  69230. */
  69231. var PoseEnabledControllerType;
  69232. (function (PoseEnabledControllerType) {
  69233. /**
  69234. * HTC Vive
  69235. */
  69236. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  69237. /**
  69238. * Oculus Rift
  69239. */
  69240. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  69241. /**
  69242. * Windows mixed reality
  69243. */
  69244. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  69245. /**
  69246. * Samsung gear VR
  69247. */
  69248. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  69249. /**
  69250. * Google Daydream
  69251. */
  69252. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  69253. /**
  69254. * Generic
  69255. */
  69256. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  69257. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  69258. /**
  69259. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  69260. */
  69261. var PoseEnabledControllerHelper = /** @class */ (function () {
  69262. function PoseEnabledControllerHelper() {
  69263. }
  69264. /**
  69265. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  69266. * @param vrGamepad the gamepad to initialized
  69267. * @returns a vr controller of the type the gamepad identified as
  69268. */
  69269. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  69270. // Oculus Touch
  69271. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  69272. return new BABYLON.OculusTouchController(vrGamepad);
  69273. }
  69274. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  69275. return new BABYLON.WindowsMotionController(vrGamepad);
  69276. }
  69277. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  69278. return new BABYLON.ViveController(vrGamepad);
  69279. }
  69280. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  69281. return new BABYLON.GearVRController(vrGamepad);
  69282. }
  69283. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  69284. return new BABYLON.DaydreamController(vrGamepad);
  69285. }
  69286. else {
  69287. return new BABYLON.GenericController(vrGamepad);
  69288. }
  69289. };
  69290. return PoseEnabledControllerHelper;
  69291. }());
  69292. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  69293. /**
  69294. * Defines the PoseEnabledController object that contains state of a vr capable controller
  69295. */
  69296. var PoseEnabledController = /** @class */ (function (_super) {
  69297. __extends(PoseEnabledController, _super);
  69298. /**
  69299. * Creates a new PoseEnabledController from a gamepad
  69300. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  69301. */
  69302. function PoseEnabledController(browserGamepad) {
  69303. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  69304. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  69305. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  69306. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  69307. /**
  69308. * The device position in babylon space
  69309. */
  69310. _this.devicePosition = BABYLON.Vector3.Zero();
  69311. /**
  69312. * The device rotation in babylon space
  69313. */
  69314. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69315. /**
  69316. * The scale factor of the device in babylon space
  69317. */
  69318. _this.deviceScaleFactor = 1;
  69319. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  69320. /**
  69321. * Internal, matrix used to convert room space to babylon space
  69322. */
  69323. _this._deviceToWorld = BABYLON.Matrix.Identity();
  69324. /**
  69325. * Node to be used when casting a ray from the controller
  69326. */
  69327. _this._pointingPoseNode = null;
  69328. _this._workingMatrix = BABYLON.Matrix.Identity();
  69329. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  69330. _this.controllerType = PoseEnabledControllerType.GENERIC;
  69331. _this.position = BABYLON.Vector3.Zero();
  69332. _this.rotationQuaternion = new BABYLON.Quaternion();
  69333. _this._calculatedPosition = BABYLON.Vector3.Zero();
  69334. _this._calculatedRotation = new BABYLON.Quaternion();
  69335. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  69336. return _this;
  69337. }
  69338. /**
  69339. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  69340. */
  69341. PoseEnabledController.prototype.update = function () {
  69342. _super.prototype.update.call(this);
  69343. var pose = this.browserGamepad.pose;
  69344. this.updateFromDevice(pose);
  69345. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  69346. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  69347. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  69348. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  69349. if (this._mesh) {
  69350. this._mesh.position.copyFrom(this.devicePosition);
  69351. if (this._mesh.rotationQuaternion) {
  69352. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69353. }
  69354. }
  69355. };
  69356. /**
  69357. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  69358. * @param poseData raw pose fromthe device
  69359. */
  69360. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  69361. if (poseData) {
  69362. this.rawPose = poseData;
  69363. if (poseData.position) {
  69364. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  69365. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  69366. this._deviceRoomPosition.z *= -1;
  69367. }
  69368. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  69369. this._calculatedPosition.addInPlace(this.position);
  69370. }
  69371. var pose = this.rawPose;
  69372. if (poseData.orientation && pose.orientation) {
  69373. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  69374. if (this._mesh) {
  69375. if (this._mesh.getScene().useRightHandedSystem) {
  69376. this._deviceRoomRotationQuaternion.z *= -1;
  69377. this._deviceRoomRotationQuaternion.w *= -1;
  69378. }
  69379. else {
  69380. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  69381. }
  69382. }
  69383. // if the camera is set, rotate to the camera's rotation
  69384. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  69385. }
  69386. }
  69387. };
  69388. /**
  69389. * Attaches a mesh to the controller
  69390. * @param mesh the mesh to be attached
  69391. */
  69392. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  69393. if (this._mesh) {
  69394. this._mesh.parent = null;
  69395. }
  69396. this._mesh = mesh;
  69397. if (this._poseControlledCamera) {
  69398. this._mesh.parent = this._poseControlledCamera;
  69399. }
  69400. if (!this._mesh.rotationQuaternion) {
  69401. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  69402. }
  69403. };
  69404. /**
  69405. * Attaches the controllers mesh to a camera
  69406. * @param camera the camera the mesh should be attached to
  69407. */
  69408. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  69409. this._poseControlledCamera = camera;
  69410. if (this._mesh) {
  69411. this._mesh.parent = this._poseControlledCamera;
  69412. }
  69413. };
  69414. /**
  69415. * Disposes of the controller
  69416. */
  69417. PoseEnabledController.prototype.dispose = function () {
  69418. if (this._mesh) {
  69419. this._mesh.dispose();
  69420. }
  69421. this._mesh = null;
  69422. _super.prototype.dispose.call(this);
  69423. };
  69424. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  69425. /**
  69426. * The mesh that is attached to the controller
  69427. */
  69428. get: function () {
  69429. return this._mesh;
  69430. },
  69431. enumerable: true,
  69432. configurable: true
  69433. });
  69434. /**
  69435. * Gets the ray of the controller in the direction the controller is pointing
  69436. * @param length the length the resulting ray should be
  69437. * @returns a ray in the direction the controller is pointing
  69438. */
  69439. PoseEnabledController.prototype.getForwardRay = function (length) {
  69440. if (length === void 0) { length = 100; }
  69441. if (!this.mesh) {
  69442. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  69443. }
  69444. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  69445. var origin = m.getTranslation();
  69446. var forward = new BABYLON.Vector3(0, 0, -1);
  69447. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  69448. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  69449. return new BABYLON.Ray(origin, direction, length);
  69450. };
  69451. /**
  69452. * Name of the child mesh that can be used to cast a ray from the controller
  69453. */
  69454. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  69455. return PoseEnabledController;
  69456. }(BABYLON.Gamepad));
  69457. BABYLON.PoseEnabledController = PoseEnabledController;
  69458. })(BABYLON || (BABYLON = {}));
  69459. //# sourceMappingURL=babylon.poseEnabledController.js.map
  69460. "use strict";
  69461. var BABYLON;
  69462. (function (BABYLON) {
  69463. /**
  69464. * Defines the WebVRController object that represents controllers tracked in 3D space
  69465. */
  69466. var WebVRController = /** @class */ (function (_super) {
  69467. __extends(WebVRController, _super);
  69468. /**
  69469. * Creates a new WebVRController from a gamepad
  69470. * @param vrGamepad the gamepad that the WebVRController should be created from
  69471. */
  69472. function WebVRController(vrGamepad) {
  69473. var _this = _super.call(this, vrGamepad) || this;
  69474. // Observables
  69475. /**
  69476. * Fired when the trigger state has changed
  69477. */
  69478. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  69479. /**
  69480. * Fired when the main button state has changed
  69481. */
  69482. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  69483. /**
  69484. * Fired when the secondary button state has changed
  69485. */
  69486. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  69487. /**
  69488. * Fired when the pad state has changed
  69489. */
  69490. _this.onPadStateChangedObservable = new BABYLON.Observable();
  69491. /**
  69492. * Fired when controllers stick values have changed
  69493. */
  69494. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  69495. /**
  69496. * X and Y axis corrisponding to the controllers joystick
  69497. */
  69498. _this.pad = { x: 0, y: 0 };
  69499. // avoid GC, store state in a tmp object
  69500. _this._changes = {
  69501. pressChanged: false,
  69502. touchChanged: false,
  69503. valueChanged: false,
  69504. changed: false
  69505. };
  69506. _this._buttons = new Array(vrGamepad.buttons.length);
  69507. _this.hand = vrGamepad.hand;
  69508. return _this;
  69509. }
  69510. /**
  69511. * Fired when a controller button's state has changed
  69512. * @param callback the callback containing the button that was modified
  69513. */
  69514. WebVRController.prototype.onButtonStateChange = function (callback) {
  69515. this._onButtonStateChange = callback;
  69516. };
  69517. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  69518. /**
  69519. * The default controller model for the controller
  69520. */
  69521. get: function () {
  69522. return this._defaultModel;
  69523. },
  69524. enumerable: true,
  69525. configurable: true
  69526. });
  69527. /**
  69528. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  69529. */
  69530. WebVRController.prototype.update = function () {
  69531. _super.prototype.update.call(this);
  69532. for (var index = 0; index < this._buttons.length; index++) {
  69533. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  69534. }
  69535. ;
  69536. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  69537. this.pad.x = this.leftStick.x;
  69538. this.pad.y = this.leftStick.y;
  69539. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  69540. }
  69541. };
  69542. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  69543. if (!newState) {
  69544. newState = {
  69545. pressed: false,
  69546. touched: false,
  69547. value: 0
  69548. };
  69549. }
  69550. if (!currentState) {
  69551. this._buttons[buttonIndex] = {
  69552. pressed: newState.pressed,
  69553. touched: newState.touched,
  69554. value: newState.value
  69555. };
  69556. return;
  69557. }
  69558. this._checkChanges(newState, currentState);
  69559. if (this._changes.changed) {
  69560. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  69561. this._handleButtonChange(buttonIndex, newState, this._changes);
  69562. }
  69563. this._buttons[buttonIndex].pressed = newState.pressed;
  69564. this._buttons[buttonIndex].touched = newState.touched;
  69565. // oculus triggers are never 0, thou not touched.
  69566. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  69567. };
  69568. WebVRController.prototype._checkChanges = function (newState, currentState) {
  69569. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  69570. this._changes.touchChanged = newState.touched !== currentState.touched;
  69571. this._changes.valueChanged = newState.value !== currentState.value;
  69572. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  69573. return this._changes;
  69574. };
  69575. /**
  69576. * Disposes of th webVRCOntroller
  69577. */
  69578. WebVRController.prototype.dispose = function () {
  69579. _super.prototype.dispose.call(this);
  69580. this.onTriggerStateChangedObservable.clear();
  69581. this.onMainButtonStateChangedObservable.clear();
  69582. this.onSecondaryButtonStateChangedObservable.clear();
  69583. this.onPadStateChangedObservable.clear();
  69584. this.onPadValuesChangedObservable.clear();
  69585. };
  69586. return WebVRController;
  69587. }(BABYLON.PoseEnabledController));
  69588. BABYLON.WebVRController = WebVRController;
  69589. })(BABYLON || (BABYLON = {}));
  69590. //# sourceMappingURL=babylon.webVRController.js.map
  69591. "use strict";
  69592. var BABYLON;
  69593. (function (BABYLON) {
  69594. /**
  69595. * Oculus Touch Controller
  69596. */
  69597. var OculusTouchController = /** @class */ (function (_super) {
  69598. __extends(OculusTouchController, _super);
  69599. /**
  69600. * Creates a new OculusTouchController from a gamepad
  69601. * @param vrGamepad the gamepad that the controller should be created from
  69602. */
  69603. function OculusTouchController(vrGamepad) {
  69604. var _this = _super.call(this, vrGamepad) || this;
  69605. /**
  69606. * Fired when the secondary trigger on this controller is modified
  69607. */
  69608. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  69609. /**
  69610. * Fired when the thumb rest on this controller is modified
  69611. */
  69612. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  69613. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  69614. return _this;
  69615. }
  69616. /**
  69617. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69618. * @param scene scene in which to add meshes
  69619. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69620. */
  69621. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69622. var _this = this;
  69623. var meshName;
  69624. // Hand
  69625. if (this.hand === 'left') {
  69626. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  69627. }
  69628. else {
  69629. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  69630. }
  69631. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  69632. /*
  69633. Parent Mesh name: oculus_touch_left
  69634. - body
  69635. - trigger
  69636. - thumbstick
  69637. - grip
  69638. - button_y
  69639. - button_x
  69640. - button_enter
  69641. */
  69642. _this._defaultModel = newMeshes[1];
  69643. _this.attachToMesh(_this._defaultModel);
  69644. if (meshLoaded) {
  69645. meshLoaded(_this._defaultModel);
  69646. }
  69647. });
  69648. };
  69649. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  69650. /**
  69651. * Fired when the A button on this controller is modified
  69652. */
  69653. get: function () {
  69654. if (this.hand === 'right') {
  69655. return this.onMainButtonStateChangedObservable;
  69656. }
  69657. else {
  69658. throw new Error('No A button on left hand');
  69659. }
  69660. },
  69661. enumerable: true,
  69662. configurable: true
  69663. });
  69664. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  69665. /**
  69666. * Fired when the B button on this controller is modified
  69667. */
  69668. get: function () {
  69669. if (this.hand === 'right') {
  69670. return this.onSecondaryButtonStateChangedObservable;
  69671. }
  69672. else {
  69673. throw new Error('No B button on left hand');
  69674. }
  69675. },
  69676. enumerable: true,
  69677. configurable: true
  69678. });
  69679. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  69680. /**
  69681. * Fired when the X button on this controller is modified
  69682. */
  69683. get: function () {
  69684. if (this.hand === 'left') {
  69685. return this.onMainButtonStateChangedObservable;
  69686. }
  69687. else {
  69688. throw new Error('No X button on right hand');
  69689. }
  69690. },
  69691. enumerable: true,
  69692. configurable: true
  69693. });
  69694. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  69695. /**
  69696. * Fired when the Y button on this controller is modified
  69697. */
  69698. get: function () {
  69699. if (this.hand === 'left') {
  69700. return this.onSecondaryButtonStateChangedObservable;
  69701. }
  69702. else {
  69703. throw new Error('No Y button on right hand');
  69704. }
  69705. },
  69706. enumerable: true,
  69707. configurable: true
  69708. });
  69709. /**
  69710. * Called once for each button that changed state since the last frame
  69711. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  69712. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  69713. * 2) secondary trigger (same)
  69714. * 3) A (right) X (left), touch, pressed = value
  69715. * 4) B / Y
  69716. * 5) thumb rest
  69717. * @param buttonIdx Which button index changed
  69718. * @param state New state of the button
  69719. * @param changes Which properties on the state changed since last frame
  69720. */
  69721. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69722. var notifyObject = state; //{ state: state, changes: changes };
  69723. var triggerDirection = this.hand === 'right' ? -1 : 1;
  69724. switch (buttonIdx) {
  69725. case 0:
  69726. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  69727. return;
  69728. case 1:// index trigger
  69729. if (this._defaultModel) {
  69730. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  69731. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  69732. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  69733. }
  69734. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  69735. return;
  69736. case 2:// secondary trigger
  69737. if (this._defaultModel) {
  69738. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  69739. }
  69740. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  69741. return;
  69742. case 3:
  69743. if (this._defaultModel) {
  69744. if (notifyObject.pressed) {
  69745. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  69746. }
  69747. else {
  69748. (this._defaultModel.getChildren()[1]).position.y = 0;
  69749. }
  69750. }
  69751. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  69752. return;
  69753. case 4:
  69754. if (this._defaultModel) {
  69755. if (notifyObject.pressed) {
  69756. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  69757. }
  69758. else {
  69759. (this._defaultModel.getChildren()[2]).position.y = 0;
  69760. }
  69761. }
  69762. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  69763. return;
  69764. case 5:
  69765. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  69766. return;
  69767. }
  69768. };
  69769. /**
  69770. * Base Url for the controller model.
  69771. */
  69772. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  69773. /**
  69774. * File name for the left controller model.
  69775. */
  69776. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  69777. /**
  69778. * File name for the right controller model.
  69779. */
  69780. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  69781. return OculusTouchController;
  69782. }(BABYLON.WebVRController));
  69783. BABYLON.OculusTouchController = OculusTouchController;
  69784. })(BABYLON || (BABYLON = {}));
  69785. //# sourceMappingURL=babylon.oculusTouchController.js.map
  69786. "use strict";
  69787. var BABYLON;
  69788. (function (BABYLON) {
  69789. /**
  69790. * Vive Controller
  69791. */
  69792. var ViveController = /** @class */ (function (_super) {
  69793. __extends(ViveController, _super);
  69794. /**
  69795. * Creates a new ViveController from a gamepad
  69796. * @param vrGamepad the gamepad that the controller should be created from
  69797. */
  69798. function ViveController(vrGamepad) {
  69799. var _this = _super.call(this, vrGamepad) || this;
  69800. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  69801. _this._invertLeftStickY = true;
  69802. return _this;
  69803. }
  69804. /**
  69805. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69806. * @param scene scene in which to add meshes
  69807. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69808. */
  69809. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69810. var _this = this;
  69811. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  69812. /*
  69813. Parent Mesh name: ViveWand
  69814. - body
  69815. - r_gripper
  69816. - l_gripper
  69817. - menu_button
  69818. - system_button
  69819. - trackpad
  69820. - trigger
  69821. - LED
  69822. */
  69823. _this._defaultModel = newMeshes[1];
  69824. _this.attachToMesh(_this._defaultModel);
  69825. if (meshLoaded) {
  69826. meshLoaded(_this._defaultModel);
  69827. }
  69828. });
  69829. };
  69830. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  69831. /**
  69832. * Fired when the left button on this controller is modified
  69833. */
  69834. get: function () {
  69835. return this.onMainButtonStateChangedObservable;
  69836. },
  69837. enumerable: true,
  69838. configurable: true
  69839. });
  69840. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  69841. /**
  69842. * Fired when the right button on this controller is modified
  69843. */
  69844. get: function () {
  69845. return this.onMainButtonStateChangedObservable;
  69846. },
  69847. enumerable: true,
  69848. configurable: true
  69849. });
  69850. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  69851. /**
  69852. * Fired when the menu button on this controller is modified
  69853. */
  69854. get: function () {
  69855. return this.onSecondaryButtonStateChangedObservable;
  69856. },
  69857. enumerable: true,
  69858. configurable: true
  69859. });
  69860. /**
  69861. * Called once for each button that changed state since the last frame
  69862. * Vive mapping:
  69863. * 0: touchpad
  69864. * 1: trigger
  69865. * 2: left AND right buttons
  69866. * 3: menu button
  69867. * @param buttonIdx Which button index changed
  69868. * @param state New state of the button
  69869. * @param changes Which properties on the state changed since last frame
  69870. */
  69871. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69872. var notifyObject = state; //{ state: state, changes: changes };
  69873. switch (buttonIdx) {
  69874. case 0:
  69875. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  69876. return;
  69877. case 1:// index trigger
  69878. if (this._defaultModel) {
  69879. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  69880. }
  69881. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  69882. return;
  69883. case 2:// left AND right button
  69884. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  69885. return;
  69886. case 3:
  69887. if (this._defaultModel) {
  69888. if (notifyObject.pressed) {
  69889. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  69890. }
  69891. else {
  69892. (this._defaultModel.getChildren()[2]).position.y = 0;
  69893. }
  69894. }
  69895. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  69896. return;
  69897. }
  69898. };
  69899. /**
  69900. * Base Url for the controller model.
  69901. */
  69902. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  69903. /**
  69904. * File name for the controller model.
  69905. */
  69906. ViveController.MODEL_FILENAME = 'wand.babylon';
  69907. return ViveController;
  69908. }(BABYLON.WebVRController));
  69909. BABYLON.ViveController = ViveController;
  69910. })(BABYLON || (BABYLON = {}));
  69911. //# sourceMappingURL=babylon.viveController.js.map
  69912. "use strict";
  69913. var BABYLON;
  69914. (function (BABYLON) {
  69915. /**
  69916. * Generic Controller
  69917. */
  69918. var GenericController = /** @class */ (function (_super) {
  69919. __extends(GenericController, _super);
  69920. /**
  69921. * Creates a new GenericController from a gamepad
  69922. * @param vrGamepad the gamepad that the controller should be created from
  69923. */
  69924. function GenericController(vrGamepad) {
  69925. return _super.call(this, vrGamepad) || this;
  69926. }
  69927. /**
  69928. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69929. * @param scene scene in which to add meshes
  69930. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69931. */
  69932. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69933. var _this = this;
  69934. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  69935. _this._defaultModel = newMeshes[1];
  69936. _this.attachToMesh(_this._defaultModel);
  69937. if (meshLoaded) {
  69938. meshLoaded(_this._defaultModel);
  69939. }
  69940. });
  69941. };
  69942. /**
  69943. * Called once for each button that changed state since the last frame
  69944. * @param buttonIdx Which button index changed
  69945. * @param state New state of the button
  69946. * @param changes Which properties on the state changed since last frame
  69947. */
  69948. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69949. console.log("Button id: " + buttonIdx + "state: ");
  69950. console.dir(state);
  69951. };
  69952. /**
  69953. * Base Url for the controller model.
  69954. */
  69955. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  69956. /**
  69957. * File name for the controller model.
  69958. */
  69959. GenericController.MODEL_FILENAME = 'generic.babylon';
  69960. return GenericController;
  69961. }(BABYLON.WebVRController));
  69962. BABYLON.GenericController = GenericController;
  69963. })(BABYLON || (BABYLON = {}));
  69964. //# sourceMappingURL=babylon.genericController.js.map
  69965. "use strict";
  69966. var BABYLON;
  69967. (function (BABYLON) {
  69968. /**
  69969. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  69970. */
  69971. var LoadedMeshInfo = /** @class */ (function () {
  69972. function LoadedMeshInfo() {
  69973. /**
  69974. * Map of the button meshes contained in the controller
  69975. */
  69976. this.buttonMeshes = {};
  69977. /**
  69978. * Map of the axis meshes contained in the controller
  69979. */
  69980. this.axisMeshes = {};
  69981. }
  69982. return LoadedMeshInfo;
  69983. }());
  69984. /**
  69985. * Defines the WindowsMotionController object that the state of the windows motion controller
  69986. */
  69987. var WindowsMotionController = /** @class */ (function (_super) {
  69988. __extends(WindowsMotionController, _super);
  69989. /**
  69990. * Creates a new WindowsMotionController from a gamepad
  69991. * @param vrGamepad the gamepad that the controller should be created from
  69992. */
  69993. function WindowsMotionController(vrGamepad) {
  69994. var _this = _super.call(this, vrGamepad) || this;
  69995. _this._mapping = {
  69996. // Semantic button names
  69997. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  69998. // A mapping of the button name to glTF model node name
  69999. // that should be transformed by button value.
  70000. buttonMeshNames: {
  70001. 'trigger': 'SELECT',
  70002. 'menu': 'MENU',
  70003. 'grip': 'GRASP',
  70004. 'thumbstick': 'THUMBSTICK_PRESS',
  70005. 'trackpad': 'TOUCHPAD_PRESS'
  70006. },
  70007. // This mapping is used to translate from the Motion Controller to Babylon semantics
  70008. buttonObservableNames: {
  70009. 'trigger': 'onTriggerStateChangedObservable',
  70010. 'menu': 'onSecondaryButtonStateChangedObservable',
  70011. 'grip': 'onMainButtonStateChangedObservable',
  70012. 'thumbstick': 'onPadStateChangedObservable',
  70013. 'trackpad': 'onTrackpadChangedObservable'
  70014. },
  70015. // A mapping of the axis name to glTF model node name
  70016. // that should be transformed by axis value.
  70017. // This array mirrors the browserGamepad.axes array, such that
  70018. // the mesh corresponding to axis 0 is in this array index 0.
  70019. axisMeshNames: [
  70020. 'THUMBSTICK_X',
  70021. 'THUMBSTICK_Y',
  70022. 'TOUCHPAD_TOUCH_X',
  70023. 'TOUCHPAD_TOUCH_Y'
  70024. ],
  70025. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  70026. };
  70027. /**
  70028. * Fired when the trackpad on this controller is clicked
  70029. */
  70030. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  70031. /**
  70032. * Fired when the trackpad on this controller is modified
  70033. */
  70034. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  70035. /**
  70036. * The current x and y values of this controller's trackpad
  70037. */
  70038. _this.trackpad = { x: 0, y: 0 };
  70039. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  70040. _this._loadedMeshInfo = null;
  70041. return _this;
  70042. }
  70043. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  70044. /**
  70045. * Fired when the trigger on this controller is modified
  70046. */
  70047. get: function () {
  70048. return this.onTriggerStateChangedObservable;
  70049. },
  70050. enumerable: true,
  70051. configurable: true
  70052. });
  70053. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  70054. /**
  70055. * Fired when the menu button on this controller is modified
  70056. */
  70057. get: function () {
  70058. return this.onSecondaryButtonStateChangedObservable;
  70059. },
  70060. enumerable: true,
  70061. configurable: true
  70062. });
  70063. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  70064. /**
  70065. * Fired when the grip button on this controller is modified
  70066. */
  70067. get: function () {
  70068. return this.onMainButtonStateChangedObservable;
  70069. },
  70070. enumerable: true,
  70071. configurable: true
  70072. });
  70073. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  70074. /**
  70075. * Fired when the thumbstick button on this controller is modified
  70076. */
  70077. get: function () {
  70078. return this.onPadStateChangedObservable;
  70079. },
  70080. enumerable: true,
  70081. configurable: true
  70082. });
  70083. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  70084. /**
  70085. * Fired when the touchpad button on this controller is modified
  70086. */
  70087. get: function () {
  70088. return this.onTrackpadChangedObservable;
  70089. },
  70090. enumerable: true,
  70091. configurable: true
  70092. });
  70093. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  70094. /**
  70095. * Fired when the touchpad values on this controller are modified
  70096. */
  70097. get: function () {
  70098. return this.onTrackpadValuesChangedObservable;
  70099. },
  70100. enumerable: true,
  70101. configurable: true
  70102. });
  70103. /**
  70104. * Called once per frame by the engine.
  70105. */
  70106. WindowsMotionController.prototype.update = function () {
  70107. _super.prototype.update.call(this);
  70108. if (this.browserGamepad.axes) {
  70109. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  70110. this.trackpad.x = this.browserGamepad["axes"][2];
  70111. this.trackpad.y = this.browserGamepad["axes"][3];
  70112. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  70113. }
  70114. // Only need to animate axes if there is a loaded mesh
  70115. if (this._loadedMeshInfo) {
  70116. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  70117. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  70118. }
  70119. }
  70120. }
  70121. };
  70122. /**
  70123. * Called once for each button that changed state since the last frame
  70124. * @param buttonIdx Which button index changed
  70125. * @param state New state of the button
  70126. * @param changes Which properties on the state changed since last frame
  70127. */
  70128. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70129. var buttonName = this._mapping.buttons[buttonIdx];
  70130. if (!buttonName) {
  70131. return;
  70132. }
  70133. // Only emit events for buttons that we know how to map from index to name
  70134. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  70135. if (observable) {
  70136. observable.notifyObservers(state);
  70137. }
  70138. this._lerpButtonTransform(buttonName, state.value);
  70139. };
  70140. /**
  70141. * Moves the buttons on the controller mesh based on their current state
  70142. * @param buttonName the name of the button to move
  70143. * @param buttonValue the value of the button which determines the buttons new position
  70144. */
  70145. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  70146. // If there is no loaded mesh, there is nothing to transform.
  70147. if (!this._loadedMeshInfo) {
  70148. return;
  70149. }
  70150. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  70151. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  70152. return;
  70153. }
  70154. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  70155. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  70156. };
  70157. /**
  70158. * Moves the axis on the controller mesh based on its current state
  70159. * @param axis the index of the axis
  70160. * @param axisValue the value of the axis which determines the meshes new position
  70161. * @ignore
  70162. */
  70163. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  70164. if (!this._loadedMeshInfo) {
  70165. return;
  70166. }
  70167. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  70168. if (!meshInfo) {
  70169. return;
  70170. }
  70171. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  70172. return;
  70173. }
  70174. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  70175. var lerpValue = axisValue * 0.5 + 0.5;
  70176. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  70177. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  70178. };
  70179. /**
  70180. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70181. * @param scene scene in which to add meshes
  70182. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70183. */
  70184. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  70185. var _this = this;
  70186. if (forceDefault === void 0) { forceDefault = false; }
  70187. var path;
  70188. var filename;
  70189. // Checking if GLB loader is present
  70190. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  70191. // Determine the device specific folder based on the ID suffix
  70192. var device = 'default';
  70193. if (this.id && !forceDefault) {
  70194. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  70195. device = ((match && match[0]) || device);
  70196. }
  70197. // Hand
  70198. if (this.hand === 'left') {
  70199. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  70200. }
  70201. else {
  70202. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  70203. }
  70204. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  70205. }
  70206. else {
  70207. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  70208. path = BABYLON.GenericController.MODEL_BASE_URL;
  70209. filename = BABYLON.GenericController.MODEL_FILENAME;
  70210. }
  70211. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  70212. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  70213. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  70214. if (!_this._loadedMeshInfo) {
  70215. return;
  70216. }
  70217. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  70218. _this.attachToMesh(_this._defaultModel);
  70219. if (meshLoaded) {
  70220. meshLoaded(_this._defaultModel);
  70221. }
  70222. }, null, function (scene, message) {
  70223. BABYLON.Tools.Log(message);
  70224. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  70225. if (!forceDefault) {
  70226. _this.initControllerMesh(scene, meshLoaded, true);
  70227. }
  70228. });
  70229. };
  70230. /**
  70231. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  70232. * can be transformed by button presses and axes values, based on this._mapping.
  70233. *
  70234. * @param scene scene in which the meshes exist
  70235. * @param meshes list of meshes that make up the controller model to process
  70236. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  70237. */
  70238. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  70239. var loadedMeshInfo = null;
  70240. // Create a new mesh to contain the glTF hierarchy
  70241. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  70242. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  70243. var childMesh = null;
  70244. for (var i = 0; i < meshes.length; i++) {
  70245. var mesh = meshes[i];
  70246. if (!mesh.parent) {
  70247. // Exclude controller meshes from picking results
  70248. mesh.isPickable = false;
  70249. // Handle root node, attach to the new parentMesh
  70250. childMesh = mesh;
  70251. break;
  70252. }
  70253. }
  70254. if (childMesh) {
  70255. childMesh.setParent(parentMesh);
  70256. // Create our mesh info. Note that this method will always return non-null.
  70257. loadedMeshInfo = this.createMeshInfo(parentMesh);
  70258. }
  70259. else {
  70260. BABYLON.Tools.Warn('Could not find root node in model file.');
  70261. }
  70262. return loadedMeshInfo;
  70263. };
  70264. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  70265. var loadedMeshInfo = new LoadedMeshInfo();
  70266. var i;
  70267. loadedMeshInfo.rootNode = rootNode;
  70268. // Reset the caches
  70269. loadedMeshInfo.buttonMeshes = {};
  70270. loadedMeshInfo.axisMeshes = {};
  70271. // Button Meshes
  70272. for (i = 0; i < this._mapping.buttons.length; i++) {
  70273. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  70274. if (!buttonMeshName) {
  70275. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  70276. continue;
  70277. }
  70278. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  70279. if (!buttonMesh) {
  70280. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  70281. continue;
  70282. }
  70283. var buttonMeshInfo = {
  70284. index: i,
  70285. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  70286. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  70287. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  70288. };
  70289. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  70290. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  70291. }
  70292. else {
  70293. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  70294. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  70295. '(VALUE: ' + !!buttonMeshInfo.value +
  70296. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  70297. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  70298. ')');
  70299. }
  70300. }
  70301. // Axis Meshes
  70302. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  70303. var axisMeshName = this._mapping.axisMeshNames[i];
  70304. if (!axisMeshName) {
  70305. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  70306. continue;
  70307. }
  70308. var axisMesh = getChildByName(rootNode, axisMeshName);
  70309. if (!axisMesh) {
  70310. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  70311. continue;
  70312. }
  70313. var axisMeshInfo = {
  70314. index: i,
  70315. value: getImmediateChildByName(axisMesh, 'VALUE'),
  70316. min: getImmediateChildByName(axisMesh, 'MIN'),
  70317. max: getImmediateChildByName(axisMesh, 'MAX')
  70318. };
  70319. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  70320. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  70321. }
  70322. else {
  70323. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  70324. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  70325. '(VALUE: ' + !!axisMeshInfo.value +
  70326. ', MIN: ' + !!axisMeshInfo.min +
  70327. ', MAX:' + !!axisMeshInfo.max +
  70328. ')');
  70329. }
  70330. }
  70331. // Pointing Ray
  70332. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  70333. if (!loadedMeshInfo.pointingPoseNode) {
  70334. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  70335. }
  70336. return loadedMeshInfo;
  70337. // Look through all children recursively. This will return null if no mesh exists with the given name.
  70338. function getChildByName(node, name) {
  70339. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  70340. }
  70341. // Look through only immediate children. This will return null if no mesh exists with the given name.
  70342. function getImmediateChildByName(node, name) {
  70343. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  70344. }
  70345. };
  70346. /**
  70347. * Gets the ray of the controller in the direction the controller is pointing
  70348. * @param length the length the resulting ray should be
  70349. * @returns a ray in the direction the controller is pointing
  70350. */
  70351. WindowsMotionController.prototype.getForwardRay = function (length) {
  70352. if (length === void 0) { length = 100; }
  70353. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  70354. return _super.prototype.getForwardRay.call(this, length);
  70355. }
  70356. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  70357. var origin = m.getTranslation();
  70358. var forward = new BABYLON.Vector3(0, 0, -1);
  70359. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70360. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70361. return new BABYLON.Ray(origin, direction, length);
  70362. };
  70363. /**
  70364. * Disposes of the controller
  70365. */
  70366. WindowsMotionController.prototype.dispose = function () {
  70367. _super.prototype.dispose.call(this);
  70368. this.onTrackpadChangedObservable.clear();
  70369. };
  70370. /**
  70371. * The base url used to load the left and right controller models
  70372. */
  70373. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  70374. /**
  70375. * The name of the left controller model file
  70376. */
  70377. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  70378. /**
  70379. * The name of the right controller model file
  70380. */
  70381. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  70382. /**
  70383. * The controller name prefix for this controller type
  70384. */
  70385. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  70386. /**
  70387. * The controller id pattern for this controller type
  70388. */
  70389. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  70390. return WindowsMotionController;
  70391. }(BABYLON.WebVRController));
  70392. BABYLON.WindowsMotionController = WindowsMotionController;
  70393. })(BABYLON || (BABYLON = {}));
  70394. //# sourceMappingURL=babylon.windowsMotionController.js.map
  70395. "use strict";
  70396. var BABYLON;
  70397. (function (BABYLON) {
  70398. /**
  70399. * Gear VR Controller
  70400. */
  70401. var GearVRController = /** @class */ (function (_super) {
  70402. __extends(GearVRController, _super);
  70403. /**
  70404. * Creates a new GearVRController from a gamepad
  70405. * @param vrGamepad the gamepad that the controller should be created from
  70406. */
  70407. function GearVRController(vrGamepad) {
  70408. var _this = _super.call(this, vrGamepad) || this;
  70409. _this._buttonIndexToObservableNameMap = [
  70410. 'onTrackpadChangedObservable',
  70411. 'onTriggerStateChangedObservable' // Trigger
  70412. ];
  70413. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  70414. return _this;
  70415. }
  70416. /**
  70417. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70418. * @param scene scene in which to add meshes
  70419. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70420. */
  70421. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70422. var _this = this;
  70423. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  70424. _this._defaultModel = newMeshes[1];
  70425. _this.attachToMesh(_this._defaultModel);
  70426. if (meshLoaded) {
  70427. meshLoaded(_this._defaultModel);
  70428. }
  70429. });
  70430. };
  70431. /**
  70432. * Called once for each button that changed state since the last frame
  70433. * @param buttonIdx Which button index changed
  70434. * @param state New state of the button
  70435. * @param changes Which properties on the state changed since last frame
  70436. */
  70437. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70438. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  70439. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  70440. // Only emit events for buttons that we know how to map from index to observable
  70441. var observable = this[observableName];
  70442. if (observable) {
  70443. observable.notifyObservers(state);
  70444. }
  70445. }
  70446. };
  70447. /**
  70448. * Base Url for the controller model.
  70449. */
  70450. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70451. /**
  70452. * File name for the controller model.
  70453. */
  70454. GearVRController.MODEL_FILENAME = 'generic.babylon';
  70455. /**
  70456. * Gamepad Id prefix used to identify this controller.
  70457. */
  70458. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  70459. return GearVRController;
  70460. }(BABYLON.WebVRController));
  70461. BABYLON.GearVRController = GearVRController;
  70462. })(BABYLON || (BABYLON = {}));
  70463. //# sourceMappingURL=babylon.gearVRController.js.map
  70464. "use strict";
  70465. var BABYLON;
  70466. (function (BABYLON) {
  70467. /**
  70468. * Google Daydream controller
  70469. */
  70470. var DaydreamController = /** @class */ (function (_super) {
  70471. __extends(DaydreamController, _super);
  70472. /**
  70473. * Creates a new DaydreamController from a gamepad
  70474. * @param vrGamepad the gamepad that the controller should be created from
  70475. */
  70476. function DaydreamController(vrGamepad) {
  70477. var _this = _super.call(this, vrGamepad) || this;
  70478. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  70479. return _this;
  70480. }
  70481. /**
  70482. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70483. * @param scene scene in which to add meshes
  70484. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70485. */
  70486. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70487. var _this = this;
  70488. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  70489. _this._defaultModel = newMeshes[1];
  70490. _this.attachToMesh(_this._defaultModel);
  70491. if (meshLoaded) {
  70492. meshLoaded(_this._defaultModel);
  70493. }
  70494. });
  70495. };
  70496. /**
  70497. * Called once for each button that changed state since the last frame
  70498. * @param buttonIdx Which button index changed
  70499. * @param state New state of the button
  70500. * @param changes Which properties on the state changed since last frame
  70501. */
  70502. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70503. // Daydream controller only has 1 GamepadButton (on the trackpad).
  70504. if (buttonIdx === 0) {
  70505. var observable = this.onTriggerStateChangedObservable;
  70506. if (observable) {
  70507. observable.notifyObservers(state);
  70508. }
  70509. }
  70510. else {
  70511. // If the app or home buttons are ever made available
  70512. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  70513. }
  70514. };
  70515. /**
  70516. * Base Url for the controller model.
  70517. */
  70518. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70519. /**
  70520. * File name for the controller model.
  70521. */
  70522. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  70523. /**
  70524. * Gamepad Id prefix used to identify Daydream Controller.
  70525. */
  70526. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  70527. return DaydreamController;
  70528. }(BABYLON.WebVRController));
  70529. BABYLON.DaydreamController = DaydreamController;
  70530. })(BABYLON || (BABYLON = {}));
  70531. //# sourceMappingURL=babylon.daydreamController.js.map
  70532. "use strict";
  70533. var BABYLON;
  70534. (function (BABYLON) {
  70535. var FollowCamera = /** @class */ (function (_super) {
  70536. __extends(FollowCamera, _super);
  70537. function FollowCamera(name, position, scene, lockedTarget) {
  70538. if (lockedTarget === void 0) { lockedTarget = null; }
  70539. var _this = _super.call(this, name, position, scene) || this;
  70540. _this.radius = 12;
  70541. _this.rotationOffset = 0;
  70542. _this.heightOffset = 4;
  70543. _this.cameraAcceleration = 0.05;
  70544. _this.maxCameraSpeed = 20;
  70545. _this.lockedTarget = lockedTarget;
  70546. return _this;
  70547. }
  70548. FollowCamera.prototype.getRadians = function (degrees) {
  70549. return degrees * Math.PI / 180;
  70550. };
  70551. FollowCamera.prototype.follow = function (cameraTarget) {
  70552. if (!cameraTarget)
  70553. return;
  70554. var yRotation;
  70555. if (cameraTarget.rotationQuaternion) {
  70556. var rotMatrix = new BABYLON.Matrix();
  70557. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  70558. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  70559. }
  70560. else {
  70561. yRotation = cameraTarget.rotation.y;
  70562. }
  70563. var radians = this.getRadians(this.rotationOffset) + yRotation;
  70564. var targetPosition = cameraTarget.getAbsolutePosition();
  70565. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  70566. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  70567. var dx = targetX - this.position.x;
  70568. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  70569. var dz = (targetZ) - this.position.z;
  70570. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  70571. var vy = dy * this.cameraAcceleration;
  70572. var vz = dz * this.cameraAcceleration * 2;
  70573. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  70574. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70575. }
  70576. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  70577. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70578. }
  70579. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  70580. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70581. }
  70582. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  70583. this.setTarget(targetPosition);
  70584. };
  70585. FollowCamera.prototype._checkInputs = function () {
  70586. _super.prototype._checkInputs.call(this);
  70587. if (this.lockedTarget) {
  70588. this.follow(this.lockedTarget);
  70589. }
  70590. };
  70591. FollowCamera.prototype.getClassName = function () {
  70592. return "FollowCamera";
  70593. };
  70594. __decorate([
  70595. BABYLON.serialize()
  70596. ], FollowCamera.prototype, "radius", void 0);
  70597. __decorate([
  70598. BABYLON.serialize()
  70599. ], FollowCamera.prototype, "rotationOffset", void 0);
  70600. __decorate([
  70601. BABYLON.serialize()
  70602. ], FollowCamera.prototype, "heightOffset", void 0);
  70603. __decorate([
  70604. BABYLON.serialize()
  70605. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  70606. __decorate([
  70607. BABYLON.serialize()
  70608. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  70609. __decorate([
  70610. BABYLON.serializeAsMeshReference("lockedTargetId")
  70611. ], FollowCamera.prototype, "lockedTarget", void 0);
  70612. return FollowCamera;
  70613. }(BABYLON.TargetCamera));
  70614. BABYLON.FollowCamera = FollowCamera;
  70615. var ArcFollowCamera = /** @class */ (function (_super) {
  70616. __extends(ArcFollowCamera, _super);
  70617. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  70618. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  70619. _this.alpha = alpha;
  70620. _this.beta = beta;
  70621. _this.radius = radius;
  70622. _this.target = target;
  70623. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  70624. _this.follow();
  70625. return _this;
  70626. }
  70627. ArcFollowCamera.prototype.follow = function () {
  70628. if (!this.target) {
  70629. return;
  70630. }
  70631. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  70632. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  70633. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  70634. var targetPosition = this.target.getAbsolutePosition();
  70635. this.position = targetPosition.add(this._cartesianCoordinates);
  70636. this.setTarget(targetPosition);
  70637. };
  70638. ArcFollowCamera.prototype._checkInputs = function () {
  70639. _super.prototype._checkInputs.call(this);
  70640. this.follow();
  70641. };
  70642. ArcFollowCamera.prototype.getClassName = function () {
  70643. return "ArcFollowCamera";
  70644. };
  70645. return ArcFollowCamera;
  70646. }(BABYLON.TargetCamera));
  70647. BABYLON.ArcFollowCamera = ArcFollowCamera;
  70648. })(BABYLON || (BABYLON = {}));
  70649. //# sourceMappingURL=babylon.followCamera.js.map
  70650. "use strict";
  70651. var BABYLON;
  70652. (function (BABYLON) {
  70653. // We're mainly based on the logic defined into the FreeCamera code
  70654. var UniversalCamera = /** @class */ (function (_super) {
  70655. __extends(UniversalCamera, _super);
  70656. //-- end properties for backward compatibility for inputs
  70657. function UniversalCamera(name, position, scene) {
  70658. var _this = _super.call(this, name, position, scene) || this;
  70659. _this.inputs.addGamepad();
  70660. return _this;
  70661. }
  70662. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  70663. //-- Begin properties for backward compatibility for inputs
  70664. get: function () {
  70665. var gamepad = this.inputs.attached["gamepad"];
  70666. if (gamepad)
  70667. return gamepad.gamepadAngularSensibility;
  70668. return 0;
  70669. },
  70670. set: function (value) {
  70671. var gamepad = this.inputs.attached["gamepad"];
  70672. if (gamepad)
  70673. gamepad.gamepadAngularSensibility = value;
  70674. },
  70675. enumerable: true,
  70676. configurable: true
  70677. });
  70678. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  70679. get: function () {
  70680. var gamepad = this.inputs.attached["gamepad"];
  70681. if (gamepad)
  70682. return gamepad.gamepadMoveSensibility;
  70683. return 0;
  70684. },
  70685. set: function (value) {
  70686. var gamepad = this.inputs.attached["gamepad"];
  70687. if (gamepad)
  70688. gamepad.gamepadMoveSensibility = value;
  70689. },
  70690. enumerable: true,
  70691. configurable: true
  70692. });
  70693. UniversalCamera.prototype.getClassName = function () {
  70694. return "UniversalCamera";
  70695. };
  70696. return UniversalCamera;
  70697. }(BABYLON.TouchCamera));
  70698. BABYLON.UniversalCamera = UniversalCamera;
  70699. })(BABYLON || (BABYLON = {}));
  70700. //# sourceMappingURL=babylon.universalCamera.js.map
  70701. "use strict";
  70702. var BABYLON;
  70703. (function (BABYLON) {
  70704. // We're mainly based on the logic defined into the FreeCamera code
  70705. var GamepadCamera = /** @class */ (function (_super) {
  70706. __extends(GamepadCamera, _super);
  70707. //-- end properties for backward compatibility for inputs
  70708. function GamepadCamera(name, position, scene) {
  70709. return _super.call(this, name, position, scene) || this;
  70710. }
  70711. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  70712. //-- Begin properties for backward compatibility for inputs
  70713. get: function () {
  70714. var gamepad = this.inputs.attached["gamepad"];
  70715. if (gamepad)
  70716. return gamepad.gamepadAngularSensibility;
  70717. return 0;
  70718. },
  70719. set: function (value) {
  70720. var gamepad = this.inputs.attached["gamepad"];
  70721. if (gamepad)
  70722. gamepad.gamepadAngularSensibility = value;
  70723. },
  70724. enumerable: true,
  70725. configurable: true
  70726. });
  70727. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  70728. get: function () {
  70729. var gamepad = this.inputs.attached["gamepad"];
  70730. if (gamepad)
  70731. return gamepad.gamepadMoveSensibility;
  70732. return 0;
  70733. },
  70734. set: function (value) {
  70735. var gamepad = this.inputs.attached["gamepad"];
  70736. if (gamepad)
  70737. gamepad.gamepadMoveSensibility = value;
  70738. },
  70739. enumerable: true,
  70740. configurable: true
  70741. });
  70742. GamepadCamera.prototype.getClassName = function () {
  70743. return "GamepadCamera";
  70744. };
  70745. return GamepadCamera;
  70746. }(BABYLON.UniversalCamera));
  70747. BABYLON.GamepadCamera = GamepadCamera;
  70748. })(BABYLON || (BABYLON = {}));
  70749. //# sourceMappingURL=babylon.gamepadCamera.js.map
  70750. "use strict";
  70751. var BABYLON;
  70752. (function (BABYLON) {
  70753. var PostProcessRenderPipelineManager = /** @class */ (function () {
  70754. function PostProcessRenderPipelineManager() {
  70755. this._renderPipelines = {};
  70756. }
  70757. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  70758. this._renderPipelines[renderPipeline._name] = renderPipeline;
  70759. };
  70760. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  70761. if (unique === void 0) { unique = false; }
  70762. var renderPipeline = this._renderPipelines[renderPipelineName];
  70763. if (!renderPipeline) {
  70764. return;
  70765. }
  70766. renderPipeline._attachCameras(cameras, unique);
  70767. };
  70768. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  70769. var renderPipeline = this._renderPipelines[renderPipelineName];
  70770. if (!renderPipeline) {
  70771. return;
  70772. }
  70773. renderPipeline._detachCameras(cameras);
  70774. };
  70775. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  70776. var renderPipeline = this._renderPipelines[renderPipelineName];
  70777. if (!renderPipeline) {
  70778. return;
  70779. }
  70780. renderPipeline._enableEffect(renderEffectName, cameras);
  70781. };
  70782. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  70783. var renderPipeline = this._renderPipelines[renderPipelineName];
  70784. if (!renderPipeline) {
  70785. return;
  70786. }
  70787. renderPipeline._disableEffect(renderEffectName, cameras);
  70788. };
  70789. PostProcessRenderPipelineManager.prototype.update = function () {
  70790. for (var renderPipelineName in this._renderPipelines) {
  70791. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70792. var pipeline = this._renderPipelines[renderPipelineName];
  70793. if (!pipeline.isSupported) {
  70794. pipeline.dispose();
  70795. delete this._renderPipelines[renderPipelineName];
  70796. }
  70797. else {
  70798. pipeline._update();
  70799. }
  70800. }
  70801. }
  70802. };
  70803. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  70804. for (var renderPipelineName in this._renderPipelines) {
  70805. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70806. var pipeline = this._renderPipelines[renderPipelineName];
  70807. pipeline._rebuild();
  70808. }
  70809. }
  70810. };
  70811. PostProcessRenderPipelineManager.prototype.dispose = function () {
  70812. for (var renderPipelineName in this._renderPipelines) {
  70813. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70814. var pipeline = this._renderPipelines[renderPipelineName];
  70815. pipeline.dispose();
  70816. }
  70817. }
  70818. };
  70819. return PostProcessRenderPipelineManager;
  70820. }());
  70821. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  70822. })(BABYLON || (BABYLON = {}));
  70823. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  70824. "use strict";
  70825. var BABYLON;
  70826. (function (BABYLON) {
  70827. /**
  70828. * This represents a set of one or more post processes in Babylon.
  70829. * A post process can be used to apply a shader to a texture after it is rendered.
  70830. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  70831. */
  70832. var PostProcessRenderEffect = /** @class */ (function () {
  70833. /**
  70834. * Instantiates a post process render effect.
  70835. * A post process can be used to apply a shader to a texture after it is rendered.
  70836. * @param engine The engine the effect is tied to
  70837. * @param name The name of the effect
  70838. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  70839. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  70840. */
  70841. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  70842. this._name = name;
  70843. this._singleInstance = singleInstance || true;
  70844. this._getPostProcesses = getPostProcesses;
  70845. this._cameras = {};
  70846. this._indicesForCamera = {};
  70847. this._postProcesses = {};
  70848. }
  70849. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  70850. /**
  70851. * Checks if all the post processes in the effect are supported.
  70852. */
  70853. get: function () {
  70854. for (var index in this._postProcesses) {
  70855. for (var ppIndex in this._postProcesses[index]) {
  70856. if (!this._postProcesses[index][ppIndex].isSupported) {
  70857. return false;
  70858. }
  70859. }
  70860. }
  70861. return true;
  70862. },
  70863. enumerable: true,
  70864. configurable: true
  70865. });
  70866. /**
  70867. * Updates the current state of the effect
  70868. */
  70869. PostProcessRenderEffect.prototype._update = function () {
  70870. };
  70871. /**
  70872. * Attaches the effect on cameras
  70873. * @param cameras The camera to attach to.
  70874. */
  70875. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  70876. var _this = this;
  70877. var cameraKey;
  70878. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70879. if (!cams) {
  70880. return;
  70881. }
  70882. for (var i = 0; i < cams.length; i++) {
  70883. var camera = cams[i];
  70884. var cameraName = camera.name;
  70885. if (this._singleInstance) {
  70886. cameraKey = 0;
  70887. }
  70888. else {
  70889. cameraKey = cameraName;
  70890. }
  70891. if (!this._postProcesses[cameraKey]) {
  70892. var postProcess = this._getPostProcesses();
  70893. if (postProcess) {
  70894. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  70895. }
  70896. }
  70897. if (!this._indicesForCamera[cameraName]) {
  70898. this._indicesForCamera[cameraName] = [];
  70899. }
  70900. this._postProcesses[cameraKey].forEach(function (postProcess) {
  70901. var index = camera.attachPostProcess(postProcess);
  70902. _this._indicesForCamera[cameraName].push(index);
  70903. });
  70904. if (!this._cameras[cameraName]) {
  70905. this._cameras[cameraName] = camera;
  70906. }
  70907. }
  70908. };
  70909. /**
  70910. * Detatches the effect on cameras
  70911. * @param cameras The camera to detatch from.
  70912. */
  70913. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  70914. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70915. if (!cams) {
  70916. return;
  70917. }
  70918. for (var i = 0; i < cams.length; i++) {
  70919. var camera = cams[i];
  70920. var cameraName = camera.name;
  70921. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70922. camera.detachPostProcess(postProcess);
  70923. });
  70924. if (this._cameras[cameraName]) {
  70925. //this._indicesForCamera.splice(index, 1);
  70926. this._cameras[cameraName] = null;
  70927. }
  70928. }
  70929. };
  70930. /**
  70931. * Enables the effect on given cameras
  70932. * @param cameras The camera to enable.
  70933. */
  70934. PostProcessRenderEffect.prototype._enable = function (cameras) {
  70935. var _this = this;
  70936. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70937. if (!cams) {
  70938. return;
  70939. }
  70940. for (var i = 0; i < cams.length; i++) {
  70941. var camera = cams[i];
  70942. var cameraName = camera.name;
  70943. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  70944. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  70945. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70946. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  70947. });
  70948. }
  70949. }
  70950. }
  70951. };
  70952. /**
  70953. * Disables the effect on the given cameras
  70954. * @param cameras The camera to disable.
  70955. */
  70956. PostProcessRenderEffect.prototype._disable = function (cameras) {
  70957. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70958. if (!cams) {
  70959. return;
  70960. }
  70961. for (var i = 0; i < cams.length; i++) {
  70962. var camera = cams[i];
  70963. var cameraName = camera.name;
  70964. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70965. camera.detachPostProcess(postProcess);
  70966. });
  70967. }
  70968. };
  70969. /**
  70970. * Gets a list of the post processes contained in the effect.
  70971. * @param camera The camera to get the post processes on.
  70972. * @returns The list of the post processes in the effect.
  70973. */
  70974. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  70975. if (this._singleInstance) {
  70976. return this._postProcesses[0];
  70977. }
  70978. else {
  70979. if (!camera) {
  70980. return null;
  70981. }
  70982. return this._postProcesses[camera.name];
  70983. }
  70984. };
  70985. return PostProcessRenderEffect;
  70986. }());
  70987. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  70988. })(BABYLON || (BABYLON = {}));
  70989. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  70990. "use strict";
  70991. var BABYLON;
  70992. (function (BABYLON) {
  70993. var PostProcessRenderPipeline = /** @class */ (function () {
  70994. function PostProcessRenderPipeline(engine, name) {
  70995. this.engine = engine;
  70996. this._name = name;
  70997. this._renderEffects = {};
  70998. this._renderEffectsForIsolatedPass = new Array();
  70999. this._cameras = [];
  71000. }
  71001. PostProcessRenderPipeline.prototype.getClassName = function () {
  71002. return "PostProcessRenderPipeline";
  71003. };
  71004. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  71005. get: function () {
  71006. for (var renderEffectName in this._renderEffects) {
  71007. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71008. if (!this._renderEffects[renderEffectName].isSupported) {
  71009. return false;
  71010. }
  71011. }
  71012. }
  71013. return true;
  71014. },
  71015. enumerable: true,
  71016. configurable: true
  71017. });
  71018. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  71019. this._renderEffects[renderEffect._name] = renderEffect;
  71020. };
  71021. // private
  71022. PostProcessRenderPipeline.prototype._rebuild = function () {
  71023. };
  71024. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  71025. var renderEffects = this._renderEffects[renderEffectName];
  71026. if (!renderEffects) {
  71027. return;
  71028. }
  71029. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71030. };
  71031. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  71032. var renderEffects = this._renderEffects[renderEffectName];
  71033. if (!renderEffects) {
  71034. return;
  71035. }
  71036. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71037. };
  71038. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  71039. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71040. if (!cams) {
  71041. return;
  71042. }
  71043. var indicesToDelete = [];
  71044. var i;
  71045. for (i = 0; i < cams.length; i++) {
  71046. var camera = cams[i];
  71047. var cameraName = camera.name;
  71048. if (this._cameras.indexOf(camera) === -1) {
  71049. this._cameras[cameraName] = camera;
  71050. }
  71051. else if (unique) {
  71052. indicesToDelete.push(i);
  71053. }
  71054. }
  71055. for (i = 0; i < indicesToDelete.length; i++) {
  71056. cameras.splice(indicesToDelete[i], 1);
  71057. }
  71058. for (var renderEffectName in this._renderEffects) {
  71059. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71060. this._renderEffects[renderEffectName]._attachCameras(cams);
  71061. }
  71062. }
  71063. };
  71064. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  71065. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71066. if (!cams) {
  71067. return;
  71068. }
  71069. for (var renderEffectName in this._renderEffects) {
  71070. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71071. this._renderEffects[renderEffectName]._detachCameras(cams);
  71072. }
  71073. }
  71074. for (var i = 0; i < cams.length; i++) {
  71075. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  71076. }
  71077. };
  71078. PostProcessRenderPipeline.prototype._update = function () {
  71079. for (var renderEffectName in this._renderEffects) {
  71080. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71081. this._renderEffects[renderEffectName]._update();
  71082. }
  71083. }
  71084. for (var i = 0; i < this._cameras.length; i++) {
  71085. var cameraName = this._cameras[i].name;
  71086. if (this._renderEffectsForIsolatedPass[cameraName]) {
  71087. this._renderEffectsForIsolatedPass[cameraName]._update();
  71088. }
  71089. }
  71090. };
  71091. PostProcessRenderPipeline.prototype._reset = function () {
  71092. this._renderEffects = {};
  71093. this._renderEffectsForIsolatedPass = new Array();
  71094. };
  71095. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  71096. // 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)
  71097. var effectKeys = Object.keys(this._renderEffects);
  71098. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  71099. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  71100. if (postProcesses) {
  71101. postProcesses[0].samples = sampleCount;
  71102. return true;
  71103. }
  71104. }
  71105. return false;
  71106. };
  71107. PostProcessRenderPipeline.prototype.dispose = function () {
  71108. // Must be implemented by children
  71109. };
  71110. __decorate([
  71111. BABYLON.serialize()
  71112. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  71113. return PostProcessRenderPipeline;
  71114. }());
  71115. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  71116. })(BABYLON || (BABYLON = {}));
  71117. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  71118. "use strict";
  71119. var BABYLON;
  71120. (function (BABYLON) {
  71121. /**
  71122. * This represents a depth renderer in Babylon.
  71123. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  71124. */
  71125. var DepthRenderer = /** @class */ (function () {
  71126. /**
  71127. * Instantiates a depth renderer
  71128. * @param scene The scene the renderer belongs to
  71129. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  71130. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  71131. */
  71132. function DepthRenderer(scene, type, camera) {
  71133. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71134. if (camera === void 0) { camera = null; }
  71135. var _this = this;
  71136. this._scene = scene;
  71137. this._camera = camera;
  71138. var engine = scene.getEngine();
  71139. // Render target
  71140. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  71141. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71142. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71143. this._depthMap.refreshRate = 1;
  71144. this._depthMap.renderParticles = false;
  71145. this._depthMap.renderList = null;
  71146. // Camera to get depth map from to support multiple concurrent cameras
  71147. this._depthMap.activeCamera = this._camera;
  71148. this._depthMap.ignoreCameraViewport = true;
  71149. this._depthMap.useCameraPostProcesses = false;
  71150. // set default depth value to 1.0 (far away)
  71151. this._depthMap.onClearObservable.add(function (engine) {
  71152. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  71153. });
  71154. // Custom render function
  71155. var renderSubMesh = function (subMesh) {
  71156. var mesh = subMesh.getRenderingMesh();
  71157. var scene = _this._scene;
  71158. var engine = scene.getEngine();
  71159. var material = subMesh.getMaterial();
  71160. if (!material) {
  71161. return;
  71162. }
  71163. // Culling and reverse (right handed system)
  71164. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71165. // Managing instances
  71166. var batch = mesh._getInstancesRenderList(subMesh._id);
  71167. if (batch.mustReturn) {
  71168. return;
  71169. }
  71170. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71171. var camera = _this._camera || scene.activeCamera;
  71172. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  71173. engine.enableEffect(_this._effect);
  71174. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71175. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71176. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  71177. // Alpha test
  71178. if (material && material.needAlphaTesting()) {
  71179. var alphaTexture = material.getAlphaTestTexture();
  71180. if (alphaTexture) {
  71181. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71182. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71183. }
  71184. }
  71185. // Bones
  71186. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71187. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71188. }
  71189. // Draw
  71190. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71191. }
  71192. };
  71193. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71194. var index;
  71195. if (depthOnlySubMeshes.length) {
  71196. engine.setColorWrite(false);
  71197. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71198. renderSubMesh(depthOnlySubMeshes.data[index]);
  71199. }
  71200. engine.setColorWrite(true);
  71201. }
  71202. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71203. renderSubMesh(opaqueSubMeshes.data[index]);
  71204. }
  71205. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71206. renderSubMesh(alphaTestSubMeshes.data[index]);
  71207. }
  71208. };
  71209. }
  71210. /**
  71211. * Creates the depth rendering effect and checks if the effect is ready.
  71212. * @param subMesh The submesh to be used to render the depth map of
  71213. * @param useInstances If multiple world instances should be used
  71214. * @returns if the depth renderer is ready to render the depth map
  71215. */
  71216. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  71217. var material = subMesh.getMaterial();
  71218. if (material.disableDepthWrite) {
  71219. return false;
  71220. }
  71221. var defines = [];
  71222. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71223. var mesh = subMesh.getMesh();
  71224. // Alpha test
  71225. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  71226. defines.push("#define ALPHATEST");
  71227. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71228. attribs.push(BABYLON.VertexBuffer.UVKind);
  71229. defines.push("#define UV1");
  71230. }
  71231. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71232. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71233. defines.push("#define UV2");
  71234. }
  71235. }
  71236. // Bones
  71237. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71238. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71239. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71240. if (mesh.numBoneInfluencers > 4) {
  71241. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71242. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71243. }
  71244. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71245. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71246. }
  71247. else {
  71248. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71249. }
  71250. // Instances
  71251. if (useInstances) {
  71252. defines.push("#define INSTANCES");
  71253. attribs.push("world0");
  71254. attribs.push("world1");
  71255. attribs.push("world2");
  71256. attribs.push("world3");
  71257. }
  71258. // Get correct effect
  71259. var join = defines.join("\n");
  71260. if (this._cachedDefines !== join) {
  71261. this._cachedDefines = join;
  71262. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  71263. }
  71264. return this._effect.isReady();
  71265. };
  71266. /**
  71267. * Gets the texture which the depth map will be written to.
  71268. * @returns The depth map texture
  71269. */
  71270. DepthRenderer.prototype.getDepthMap = function () {
  71271. return this._depthMap;
  71272. };
  71273. /**
  71274. * Disposes of the depth renderer.
  71275. */
  71276. DepthRenderer.prototype.dispose = function () {
  71277. this._depthMap.dispose();
  71278. };
  71279. return DepthRenderer;
  71280. }());
  71281. BABYLON.DepthRenderer = DepthRenderer;
  71282. })(BABYLON || (BABYLON = {}));
  71283. //# sourceMappingURL=babylon.depthRenderer.js.map
  71284. "use strict";
  71285. var BABYLON;
  71286. (function (BABYLON) {
  71287. var SSAORenderingPipeline = /** @class */ (function (_super) {
  71288. __extends(SSAORenderingPipeline, _super);
  71289. /**
  71290. * @constructor
  71291. * @param {string} name - The rendering pipeline name
  71292. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71293. * @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 }
  71294. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71295. */
  71296. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  71297. var _this = _super.call(this, scene.getEngine(), name) || this;
  71298. // Members
  71299. /**
  71300. * The PassPostProcess id in the pipeline that contains the original scene color
  71301. */
  71302. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  71303. /**
  71304. * The SSAO PostProcess id in the pipeline
  71305. */
  71306. _this.SSAORenderEffect = "SSAORenderEffect";
  71307. /**
  71308. * The horizontal blur PostProcess id in the pipeline
  71309. */
  71310. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71311. /**
  71312. * The vertical blur PostProcess id in the pipeline
  71313. */
  71314. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71315. /**
  71316. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71317. */
  71318. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71319. /**
  71320. * The output strength of the SSAO post-process. Default value is 1.0.
  71321. */
  71322. _this.totalStrength = 1.0;
  71323. /**
  71324. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  71325. */
  71326. _this.radius = 0.0001;
  71327. /**
  71328. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  71329. * Must not be equal to fallOff and superior to fallOff.
  71330. * Default value is 0.975
  71331. */
  71332. _this.area = 0.0075;
  71333. /**
  71334. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  71335. * Must not be equal to area and inferior to area.
  71336. * Default value is 0.0
  71337. */
  71338. _this.fallOff = 0.000001;
  71339. /**
  71340. * The base color of the SSAO post-process
  71341. * The final result is "base + ssao" between [0, 1]
  71342. */
  71343. _this.base = 0.5;
  71344. _this._firstUpdate = true;
  71345. _this._scene = scene;
  71346. // Set up assets
  71347. _this._createRandomTexture();
  71348. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  71349. var ssaoRatio = ratio.ssaoRatio || ratio;
  71350. var combineRatio = ratio.combineRatio || ratio;
  71351. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71352. _this._createSSAOPostProcess(ssaoRatio);
  71353. _this._createBlurPostProcess(ssaoRatio);
  71354. _this._createSSAOCombinePostProcess(combineRatio);
  71355. // Set up pipeline
  71356. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71357. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71358. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71359. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71360. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71361. // Finish
  71362. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71363. if (cameras)
  71364. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71365. return _this;
  71366. }
  71367. // Public Methods
  71368. /**
  71369. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71370. */
  71371. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  71372. if (disableDepthRender === void 0) { disableDepthRender = false; }
  71373. for (var i = 0; i < this._scene.cameras.length; i++) {
  71374. var camera = this._scene.cameras[i];
  71375. this._originalColorPostProcess.dispose(camera);
  71376. this._ssaoPostProcess.dispose(camera);
  71377. this._blurHPostProcess.dispose(camera);
  71378. this._blurVPostProcess.dispose(camera);
  71379. this._ssaoCombinePostProcess.dispose(camera);
  71380. }
  71381. this._randomTexture.dispose();
  71382. if (disableDepthRender)
  71383. this._scene.disableDepthRenderer();
  71384. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71385. _super.prototype.dispose.call(this);
  71386. };
  71387. // Private Methods
  71388. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  71389. var _this = this;
  71390. var size = 16;
  71391. 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);
  71392. 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);
  71393. this._blurHPostProcess.onActivateObservable.add(function () {
  71394. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  71395. _this._blurHPostProcess.kernel = size * dw;
  71396. });
  71397. this._blurVPostProcess.onActivateObservable.add(function () {
  71398. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  71399. _this._blurVPostProcess.kernel = size * dw;
  71400. });
  71401. };
  71402. SSAORenderingPipeline.prototype._rebuild = function () {
  71403. this._firstUpdate = true;
  71404. _super.prototype._rebuild.call(this);
  71405. };
  71406. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  71407. var _this = this;
  71408. var numSamples = 16;
  71409. var sampleSphere = [
  71410. 0.5381, 0.1856, -0.4319,
  71411. 0.1379, 0.2486, 0.4430,
  71412. 0.3371, 0.5679, -0.0057,
  71413. -0.6999, -0.0451, -0.0019,
  71414. 0.0689, -0.1598, -0.8547,
  71415. 0.0560, 0.0069, -0.1843,
  71416. -0.0146, 0.1402, 0.0762,
  71417. 0.0100, -0.1924, -0.0344,
  71418. -0.3577, -0.5301, -0.4358,
  71419. -0.3169, 0.1063, 0.0158,
  71420. 0.0103, -0.5869, 0.0046,
  71421. -0.0897, -0.4940, 0.3287,
  71422. 0.7119, -0.0154, -0.0918,
  71423. -0.0533, 0.0596, -0.5411,
  71424. 0.0352, -0.0631, 0.5460,
  71425. -0.4776, 0.2847, -0.0271
  71426. ];
  71427. var samplesFactor = 1.0 / numSamples;
  71428. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  71429. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  71430. "area", "fallOff", "base", "range", "viewport"
  71431. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  71432. this._ssaoPostProcess.onApply = function (effect) {
  71433. if (_this._firstUpdate) {
  71434. effect.setArray3("sampleSphere", sampleSphere);
  71435. effect.setFloat("samplesFactor", samplesFactor);
  71436. effect.setFloat("randTextureTiles", 4.0);
  71437. }
  71438. effect.setFloat("totalStrength", _this.totalStrength);
  71439. effect.setFloat("radius", _this.radius);
  71440. effect.setFloat("area", _this.area);
  71441. effect.setFloat("fallOff", _this.fallOff);
  71442. effect.setFloat("base", _this.base);
  71443. effect.setTexture("textureSampler", _this._depthTexture);
  71444. effect.setTexture("randomSampler", _this._randomTexture);
  71445. };
  71446. };
  71447. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71448. var _this = this;
  71449. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71450. this._ssaoCombinePostProcess.onApply = function (effect) {
  71451. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  71452. };
  71453. };
  71454. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  71455. var size = 512;
  71456. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71457. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71458. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71459. var context = this._randomTexture.getContext();
  71460. var rand = function (min, max) {
  71461. return Math.random() * (max - min) + min;
  71462. };
  71463. var randVector = BABYLON.Vector3.Zero();
  71464. for (var x = 0; x < size; x++) {
  71465. for (var y = 0; y < size; y++) {
  71466. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  71467. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  71468. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  71469. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  71470. context.fillRect(x, y, 1, 1);
  71471. }
  71472. }
  71473. this._randomTexture.update(false);
  71474. };
  71475. __decorate([
  71476. BABYLON.serialize()
  71477. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  71478. __decorate([
  71479. BABYLON.serialize()
  71480. ], SSAORenderingPipeline.prototype, "radius", void 0);
  71481. __decorate([
  71482. BABYLON.serialize()
  71483. ], SSAORenderingPipeline.prototype, "area", void 0);
  71484. __decorate([
  71485. BABYLON.serialize()
  71486. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  71487. __decorate([
  71488. BABYLON.serialize()
  71489. ], SSAORenderingPipeline.prototype, "base", void 0);
  71490. return SSAORenderingPipeline;
  71491. }(BABYLON.PostProcessRenderPipeline));
  71492. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  71493. })(BABYLON || (BABYLON = {}));
  71494. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  71495. "use strict";
  71496. var BABYLON;
  71497. (function (BABYLON) {
  71498. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  71499. __extends(SSAO2RenderingPipeline, _super);
  71500. /**
  71501. * @constructor
  71502. * @param {string} name - The rendering pipeline name
  71503. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71504. * @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 }
  71505. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71506. */
  71507. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  71508. var _this = _super.call(this, scene.getEngine(), name) || this;
  71509. // Members
  71510. /**
  71511. * The PassPostProcess id in the pipeline that contains the original scene color
  71512. */
  71513. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  71514. /**
  71515. * The SSAO PostProcess id in the pipeline
  71516. */
  71517. _this.SSAORenderEffect = "SSAORenderEffect";
  71518. /**
  71519. * The horizontal blur PostProcess id in the pipeline
  71520. */
  71521. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71522. /**
  71523. * The vertical blur PostProcess id in the pipeline
  71524. */
  71525. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71526. /**
  71527. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71528. */
  71529. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71530. /**
  71531. * The output strength of the SSAO post-process. Default value is 1.0.
  71532. */
  71533. _this.totalStrength = 1.0;
  71534. /**
  71535. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  71536. */
  71537. _this.maxZ = 100.0;
  71538. /**
  71539. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  71540. */
  71541. _this.minZAspect = 0.2;
  71542. /**
  71543. * Number of samples used for the SSAO calculations. Default value is 8
  71544. */
  71545. _this._samples = 8;
  71546. /**
  71547. * Are we using bilateral blur ?
  71548. */
  71549. _this._expensiveBlur = true;
  71550. /**
  71551. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  71552. */
  71553. _this.radius = 2.0;
  71554. /**
  71555. * The base color of the SSAO post-process
  71556. * The final result is "base + ssao" between [0, 1]
  71557. */
  71558. _this.base = 0.1;
  71559. _this._firstUpdate = true;
  71560. _this._scene = scene;
  71561. if (!_this.isSupported) {
  71562. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  71563. return _this;
  71564. }
  71565. var ssaoRatio = ratio.ssaoRatio || ratio;
  71566. var blurRatio = ratio.blurRatio || ratio;
  71567. // Set up assets
  71568. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  71569. _this._createRandomTexture();
  71570. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  71571. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  71572. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71573. _this._createSSAOPostProcess(1.0);
  71574. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  71575. _this._createSSAOCombinePostProcess(blurRatio);
  71576. // Set up pipeline
  71577. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71578. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71579. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71580. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71581. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71582. // Finish
  71583. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71584. if (cameras)
  71585. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71586. return _this;
  71587. }
  71588. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  71589. get: function () {
  71590. return this._samples;
  71591. },
  71592. set: function (n) {
  71593. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  71594. this._samples = n;
  71595. this._sampleSphere = this._generateHemisphere();
  71596. this._firstUpdate = true;
  71597. },
  71598. enumerable: true,
  71599. configurable: true
  71600. });
  71601. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  71602. get: function () {
  71603. return this._expensiveBlur;
  71604. },
  71605. set: function (b) {
  71606. 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"]);
  71607. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  71608. this._expensiveBlur = b;
  71609. this._firstUpdate = true;
  71610. },
  71611. enumerable: true,
  71612. configurable: true
  71613. });
  71614. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  71615. /**
  71616. * Support test.
  71617. */
  71618. get: function () {
  71619. var engine = BABYLON.Engine.LastCreatedEngine;
  71620. if (!engine) {
  71621. return false;
  71622. }
  71623. return engine.getCaps().drawBuffersExtension;
  71624. },
  71625. enumerable: true,
  71626. configurable: true
  71627. });
  71628. // Public Methods
  71629. /**
  71630. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71631. */
  71632. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  71633. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  71634. for (var i = 0; i < this._scene.cameras.length; i++) {
  71635. var camera = this._scene.cameras[i];
  71636. this._originalColorPostProcess.dispose(camera);
  71637. this._ssaoPostProcess.dispose(camera);
  71638. this._blurHPostProcess.dispose(camera);
  71639. this._blurVPostProcess.dispose(camera);
  71640. this._ssaoCombinePostProcess.dispose(camera);
  71641. }
  71642. this._randomTexture.dispose();
  71643. if (disableGeometryBufferRenderer)
  71644. this._scene.disableGeometryBufferRenderer();
  71645. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71646. _super.prototype.dispose.call(this);
  71647. };
  71648. // Private Methods
  71649. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  71650. var _this = this;
  71651. this._samplerOffsets = [];
  71652. var expensive = this.expensiveBlur;
  71653. for (var i = -8; i < 8; i++) {
  71654. this._samplerOffsets.push(i * 2 + 0.5);
  71655. }
  71656. 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");
  71657. this._blurHPostProcess.onApply = function (effect) {
  71658. if (!_this._scene.activeCamera) {
  71659. return;
  71660. }
  71661. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  71662. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71663. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71664. effect.setFloat("radius", _this.radius);
  71665. effect.setTexture("depthSampler", _this._depthTexture);
  71666. if (_this._firstUpdate) {
  71667. effect.setArray("samplerOffsets", _this._samplerOffsets);
  71668. }
  71669. };
  71670. 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");
  71671. this._blurVPostProcess.onApply = function (effect) {
  71672. if (!_this._scene.activeCamera) {
  71673. return;
  71674. }
  71675. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  71676. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71677. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71678. effect.setFloat("radius", _this.radius);
  71679. effect.setTexture("depthSampler", _this._depthTexture);
  71680. if (_this._firstUpdate) {
  71681. effect.setArray("samplerOffsets", _this._samplerOffsets);
  71682. _this._firstUpdate = false;
  71683. }
  71684. };
  71685. };
  71686. SSAO2RenderingPipeline.prototype._rebuild = function () {
  71687. this._firstUpdate = true;
  71688. _super.prototype._rebuild.call(this);
  71689. };
  71690. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  71691. var numSamples = this.samples;
  71692. var result = [];
  71693. var vector, scale;
  71694. var rand = function (min, max) {
  71695. return Math.random() * (max - min) + min;
  71696. };
  71697. var i = 0;
  71698. while (i < numSamples) {
  71699. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  71700. vector.normalize();
  71701. scale = i / numSamples;
  71702. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  71703. vector.scaleInPlace(scale);
  71704. result.push(vector.x, vector.y, vector.z);
  71705. i++;
  71706. }
  71707. return result;
  71708. };
  71709. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  71710. var _this = this;
  71711. var numSamples = this.samples;
  71712. this._sampleSphere = this._generateHemisphere();
  71713. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  71714. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  71715. "base", "range", "projection", "near", "far", "texelSize",
  71716. "xViewport", "yViewport", "maxZ", "minZAspect"
  71717. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  71718. this._ssaoPostProcess.onApply = function (effect) {
  71719. if (_this._firstUpdate) {
  71720. effect.setArray3("sampleSphere", _this._sampleSphere);
  71721. effect.setFloat("randTextureTiles", 4.0);
  71722. }
  71723. if (!_this._scene.activeCamera) {
  71724. return;
  71725. }
  71726. effect.setFloat("samplesFactor", 1 / _this.samples);
  71727. effect.setFloat("totalStrength", _this.totalStrength);
  71728. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  71729. effect.setFloat("radius", _this.radius);
  71730. effect.setFloat("maxZ", _this.maxZ);
  71731. effect.setFloat("minZAspect", _this.minZAspect);
  71732. effect.setFloat("base", _this.base);
  71733. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71734. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71735. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  71736. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  71737. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  71738. effect.setTexture("textureSampler", _this._depthTexture);
  71739. effect.setTexture("normalSampler", _this._normalTexture);
  71740. effect.setTexture("randomSampler", _this._randomTexture);
  71741. };
  71742. };
  71743. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71744. var _this = this;
  71745. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71746. this._ssaoCombinePostProcess.onApply = function (effect) {
  71747. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  71748. };
  71749. };
  71750. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  71751. var size = 512;
  71752. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71753. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71754. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71755. var context = this._randomTexture.getContext();
  71756. var rand = function (min, max) {
  71757. return Math.random() * (max - min) + min;
  71758. };
  71759. var randVector = BABYLON.Vector3.Zero();
  71760. for (var x = 0; x < size; x++) {
  71761. for (var y = 0; y < size; y++) {
  71762. randVector.x = rand(0.0, 1.0);
  71763. randVector.y = rand(0.0, 1.0);
  71764. randVector.z = 0.0;
  71765. randVector.normalize();
  71766. randVector.scaleInPlace(255);
  71767. randVector.x = Math.floor(randVector.x);
  71768. randVector.y = Math.floor(randVector.y);
  71769. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  71770. context.fillRect(x, y, 1, 1);
  71771. }
  71772. }
  71773. this._randomTexture.update(false);
  71774. };
  71775. __decorate([
  71776. BABYLON.serialize()
  71777. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  71778. __decorate([
  71779. BABYLON.serialize()
  71780. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  71781. __decorate([
  71782. BABYLON.serialize()
  71783. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  71784. __decorate([
  71785. BABYLON.serialize("samples")
  71786. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  71787. __decorate([
  71788. BABYLON.serialize("expensiveBlur")
  71789. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  71790. __decorate([
  71791. BABYLON.serialize()
  71792. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  71793. __decorate([
  71794. BABYLON.serialize()
  71795. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  71796. return SSAO2RenderingPipeline;
  71797. }(BABYLON.PostProcessRenderPipeline));
  71798. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  71799. })(BABYLON || (BABYLON = {}));
  71800. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  71801. "use strict";
  71802. // BABYLON.JS Chromatic Aberration GLSL Shader
  71803. // Author: Olivier Guyot
  71804. // Separates very slightly R, G and B colors on the edges of the screen
  71805. // Inspired by Francois Tarlier & Martins Upitis
  71806. var BABYLON;
  71807. (function (BABYLON) {
  71808. var LensRenderingPipeline = /** @class */ (function (_super) {
  71809. __extends(LensRenderingPipeline, _super);
  71810. /**
  71811. * @constructor
  71812. *
  71813. * Effect parameters are as follow:
  71814. * {
  71815. * chromatic_aberration: number; // from 0 to x (1 for realism)
  71816. * edge_blur: number; // from 0 to x (1 for realism)
  71817. * distortion: number; // from 0 to x (1 for realism)
  71818. * grain_amount: number; // from 0 to 1
  71819. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  71820. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  71821. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  71822. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  71823. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  71824. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  71825. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  71826. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  71827. * }
  71828. * Note: if an effect parameter is unset, effect is disabled
  71829. *
  71830. * @param {string} name - The rendering pipeline name
  71831. * @param {object} parameters - An object containing all parameters (see above)
  71832. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71833. * @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)
  71834. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71835. */
  71836. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  71837. if (ratio === void 0) { ratio = 1.0; }
  71838. var _this = _super.call(this, scene.getEngine(), name) || this;
  71839. // Lens effects can be of the following:
  71840. // - chromatic aberration (slight shift of RGB colors)
  71841. // - blur on the edge of the lens
  71842. // - lens distortion
  71843. // - depth-of-field blur & highlights enhancing
  71844. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  71845. // - grain effect (noise or custom texture)
  71846. // Two additional texture samplers are needed:
  71847. // - depth map (for depth-of-field)
  71848. // - grain texture
  71849. /**
  71850. * The chromatic aberration PostProcess id in the pipeline
  71851. */
  71852. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  71853. /**
  71854. * The highlights enhancing PostProcess id in the pipeline
  71855. */
  71856. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  71857. /**
  71858. * The depth-of-field PostProcess id in the pipeline
  71859. */
  71860. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  71861. _this._scene = scene;
  71862. // Fetch texture samplers
  71863. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  71864. if (parameters.grain_texture) {
  71865. _this._grainTexture = parameters.grain_texture;
  71866. }
  71867. else {
  71868. _this._createGrainTexture();
  71869. }
  71870. // save parameters
  71871. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  71872. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  71873. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  71874. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  71875. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  71876. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  71877. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  71878. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  71879. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  71880. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  71881. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  71882. // Create effects
  71883. _this._createChromaticAberrationPostProcess(ratio);
  71884. _this._createHighlightsPostProcess(ratio);
  71885. _this._createDepthOfFieldPostProcess(ratio / 4);
  71886. // Set up pipeline
  71887. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  71888. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  71889. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  71890. if (_this._highlightsGain === -1) {
  71891. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  71892. }
  71893. // Finish
  71894. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71895. if (cameras) {
  71896. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71897. }
  71898. return _this;
  71899. }
  71900. // public methods (self explanatory)
  71901. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  71902. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  71903. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  71904. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  71905. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  71906. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  71907. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  71908. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  71909. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  71910. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  71911. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  71912. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  71913. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  71914. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  71915. };
  71916. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  71917. this._highlightsPostProcess.updateEffect();
  71918. };
  71919. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  71920. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  71921. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  71922. this._highlightsGain = amount;
  71923. };
  71924. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  71925. if (this._highlightsGain === -1) {
  71926. this._highlightsGain = 1.0;
  71927. }
  71928. this._highlightsThreshold = amount;
  71929. };
  71930. LensRenderingPipeline.prototype.disableHighlights = function () {
  71931. this._highlightsGain = -1;
  71932. };
  71933. /**
  71934. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  71935. */
  71936. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  71937. if (disableDepthRender === void 0) { disableDepthRender = false; }
  71938. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71939. this._chromaticAberrationPostProcess = null;
  71940. this._highlightsPostProcess = null;
  71941. this._depthOfFieldPostProcess = null;
  71942. this._grainTexture.dispose();
  71943. if (disableDepthRender)
  71944. this._scene.disableDepthRenderer();
  71945. };
  71946. // colors shifting and distortion
  71947. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  71948. var _this = this;
  71949. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  71950. [], // samplers
  71951. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71952. this._chromaticAberrationPostProcess.onApply = function (effect) {
  71953. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  71954. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71955. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71956. effect.setFloat('radialIntensity', 1);
  71957. effect.setFloat2('direction', 17, 17);
  71958. effect.setFloat2('centerPosition', 0.5, 0.5);
  71959. };
  71960. };
  71961. // highlights enhancing
  71962. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  71963. var _this = this;
  71964. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  71965. [], // samplers
  71966. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  71967. this._highlightsPostProcess.onApply = function (effect) {
  71968. effect.setFloat('gain', _this._highlightsGain);
  71969. effect.setFloat('threshold', _this._highlightsThreshold);
  71970. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  71971. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71972. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71973. };
  71974. };
  71975. // colors shifting and distortion
  71976. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  71977. var _this = this;
  71978. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  71979. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  71980. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  71981. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71982. this._depthOfFieldPostProcess.onApply = function (effect) {
  71983. effect.setTexture("depthSampler", _this._depthTexture);
  71984. effect.setTexture("grainSampler", _this._grainTexture);
  71985. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  71986. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  71987. effect.setFloat('grain_amount', _this._grainAmount);
  71988. effect.setBool('blur_noise', _this._blurNoise);
  71989. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71990. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71991. effect.setFloat('distortion', _this._distortion);
  71992. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  71993. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  71994. effect.setFloat('aperture', _this._dofAperture);
  71995. effect.setFloat('darken', _this._dofDarken);
  71996. effect.setFloat('edge_blur', _this._edgeBlur);
  71997. effect.setBool('highlights', (_this._highlightsGain !== -1));
  71998. if (_this._scene.activeCamera) {
  71999. effect.setFloat('near', _this._scene.activeCamera.minZ);
  72000. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  72001. }
  72002. };
  72003. };
  72004. // creates a black and white random noise texture, 512x512
  72005. LensRenderingPipeline.prototype._createGrainTexture = function () {
  72006. var size = 512;
  72007. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72008. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72009. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72010. var context = this._grainTexture.getContext();
  72011. var rand = function (min, max) {
  72012. return Math.random() * (max - min) + min;
  72013. };
  72014. var value;
  72015. for (var x = 0; x < size; x++) {
  72016. for (var y = 0; y < size; y++) {
  72017. value = Math.floor(rand(0.42, 0.58) * 255);
  72018. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  72019. context.fillRect(x, y, 1, 1);
  72020. }
  72021. }
  72022. this._grainTexture.update(false);
  72023. };
  72024. return LensRenderingPipeline;
  72025. }(BABYLON.PostProcessRenderPipeline));
  72026. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  72027. })(BABYLON || (BABYLON = {}));
  72028. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  72029. "use strict";
  72030. var BABYLON;
  72031. (function (BABYLON) {
  72032. var StandardRenderingPipeline = /** @class */ (function (_super) {
  72033. __extends(StandardRenderingPipeline, _super);
  72034. /**
  72035. * @constructor
  72036. * @param {string} name - The rendering pipeline name
  72037. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72038. * @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)
  72039. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  72040. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72041. */
  72042. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  72043. if (originalPostProcess === void 0) { originalPostProcess = null; }
  72044. var _this = _super.call(this, scene.getEngine(), name) || this;
  72045. _this.downSampleX4PostProcess = null;
  72046. _this.brightPassPostProcess = null;
  72047. _this.blurHPostProcesses = [];
  72048. _this.blurVPostProcesses = [];
  72049. _this.textureAdderPostProcess = null;
  72050. _this.volumetricLightPostProcess = null;
  72051. _this.volumetricLightSmoothXPostProcess = null;
  72052. _this.volumetricLightSmoothYPostProcess = null;
  72053. _this.volumetricLightMergePostProces = null;
  72054. _this.volumetricLightFinalPostProcess = null;
  72055. _this.luminancePostProcess = null;
  72056. _this.luminanceDownSamplePostProcesses = [];
  72057. _this.hdrPostProcess = null;
  72058. _this.textureAdderFinalPostProcess = null;
  72059. _this.lensFlareFinalPostProcess = null;
  72060. _this.hdrFinalPostProcess = null;
  72061. _this.lensFlarePostProcess = null;
  72062. _this.lensFlareComposePostProcess = null;
  72063. _this.motionBlurPostProcess = null;
  72064. _this.depthOfFieldPostProcess = null;
  72065. // Values
  72066. _this.brightThreshold = 1.0;
  72067. _this.blurWidth = 512.0;
  72068. _this.horizontalBlur = false;
  72069. _this.exposure = 1.0;
  72070. _this.lensTexture = null;
  72071. _this.volumetricLightCoefficient = 0.2;
  72072. _this.volumetricLightPower = 4.0;
  72073. _this.volumetricLightBlurScale = 64.0;
  72074. _this.sourceLight = null;
  72075. _this.hdrMinimumLuminance = 1.0;
  72076. _this.hdrDecreaseRate = 0.5;
  72077. _this.hdrIncreaseRate = 0.5;
  72078. _this.lensColorTexture = null;
  72079. _this.lensFlareStrength = 20.0;
  72080. _this.lensFlareGhostDispersal = 1.4;
  72081. _this.lensFlareHaloWidth = 0.7;
  72082. _this.lensFlareDistortionStrength = 16.0;
  72083. _this.lensStarTexture = null;
  72084. _this.lensFlareDirtTexture = null;
  72085. _this.depthOfFieldDistance = 10.0;
  72086. _this.depthOfFieldBlurWidth = 64.0;
  72087. _this.motionStrength = 1.0;
  72088. // IAnimatable
  72089. _this.animations = [];
  72090. _this._currentDepthOfFieldSource = null;
  72091. _this._hdrCurrentLuminance = 1.0;
  72092. // Getters and setters
  72093. _this._bloomEnabled = true;
  72094. _this._depthOfFieldEnabled = false;
  72095. _this._vlsEnabled = false;
  72096. _this._lensFlareEnabled = false;
  72097. _this._hdrEnabled = false;
  72098. _this._motionBlurEnabled = false;
  72099. _this._motionBlurSamples = 64.0;
  72100. _this._volumetricLightStepsCount = 50.0;
  72101. _this._cameras = cameras || [];
  72102. // Initialize
  72103. _this._scene = scene;
  72104. _this._basePostProcess = originalPostProcess;
  72105. _this._ratio = ratio;
  72106. // Misc
  72107. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72108. // Finish
  72109. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72110. _this._buildPipeline();
  72111. return _this;
  72112. }
  72113. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  72114. get: function () {
  72115. return this._bloomEnabled;
  72116. },
  72117. set: function (enabled) {
  72118. if (this._bloomEnabled === enabled) {
  72119. return;
  72120. }
  72121. this._bloomEnabled = enabled;
  72122. this._buildPipeline();
  72123. },
  72124. enumerable: true,
  72125. configurable: true
  72126. });
  72127. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  72128. get: function () {
  72129. return this._depthOfFieldEnabled;
  72130. },
  72131. set: function (enabled) {
  72132. if (this._depthOfFieldEnabled === enabled) {
  72133. return;
  72134. }
  72135. this._depthOfFieldEnabled = enabled;
  72136. this._buildPipeline();
  72137. },
  72138. enumerable: true,
  72139. configurable: true
  72140. });
  72141. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  72142. get: function () {
  72143. return this._lensFlareEnabled;
  72144. },
  72145. set: function (enabled) {
  72146. if (this._lensFlareEnabled === enabled) {
  72147. return;
  72148. }
  72149. this._lensFlareEnabled = enabled;
  72150. this._buildPipeline();
  72151. },
  72152. enumerable: true,
  72153. configurable: true
  72154. });
  72155. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  72156. get: function () {
  72157. return this._hdrEnabled;
  72158. },
  72159. set: function (enabled) {
  72160. if (this._hdrEnabled === enabled) {
  72161. return;
  72162. }
  72163. this._hdrEnabled = enabled;
  72164. this._buildPipeline();
  72165. },
  72166. enumerable: true,
  72167. configurable: true
  72168. });
  72169. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  72170. get: function () {
  72171. return this._vlsEnabled;
  72172. },
  72173. set: function (enabled) {
  72174. if (this._vlsEnabled === enabled) {
  72175. return;
  72176. }
  72177. if (enabled) {
  72178. var geometry = this._scene.enableGeometryBufferRenderer();
  72179. if (!geometry) {
  72180. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  72181. return;
  72182. }
  72183. }
  72184. this._vlsEnabled = enabled;
  72185. this._buildPipeline();
  72186. },
  72187. enumerable: true,
  72188. configurable: true
  72189. });
  72190. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  72191. get: function () {
  72192. return this._motionBlurEnabled;
  72193. },
  72194. set: function (enabled) {
  72195. if (this._motionBlurEnabled === enabled) {
  72196. return;
  72197. }
  72198. this._motionBlurEnabled = enabled;
  72199. this._buildPipeline();
  72200. },
  72201. enumerable: true,
  72202. configurable: true
  72203. });
  72204. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  72205. get: function () {
  72206. return this._volumetricLightStepsCount;
  72207. },
  72208. set: function (count) {
  72209. if (this.volumetricLightPostProcess) {
  72210. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  72211. }
  72212. this._volumetricLightStepsCount = count;
  72213. },
  72214. enumerable: true,
  72215. configurable: true
  72216. });
  72217. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  72218. get: function () {
  72219. return this._motionBlurSamples;
  72220. },
  72221. set: function (samples) {
  72222. if (this.motionBlurPostProcess) {
  72223. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  72224. }
  72225. this._motionBlurSamples = samples;
  72226. },
  72227. enumerable: true,
  72228. configurable: true
  72229. });
  72230. StandardRenderingPipeline.prototype._buildPipeline = function () {
  72231. var _this = this;
  72232. var ratio = this._ratio;
  72233. var scene = this._scene;
  72234. this._disposePostProcesses();
  72235. this._reset();
  72236. // Create pass post-process
  72237. if (!this._basePostProcess) {
  72238. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  72239. this.originalPostProcess.onApply = function (effect) {
  72240. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  72241. };
  72242. }
  72243. else {
  72244. this.originalPostProcess = this._basePostProcess;
  72245. }
  72246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  72247. this._currentDepthOfFieldSource = this.originalPostProcess;
  72248. if (this._vlsEnabled) {
  72249. // Create volumetric light
  72250. this._createVolumetricLightPostProcess(scene, ratio);
  72251. // Create volumetric light final post-process
  72252. 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);
  72253. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  72254. }
  72255. if (this._bloomEnabled) {
  72256. // Create down sample X4 post-process
  72257. this._createDownSampleX4PostProcess(scene, ratio / 2);
  72258. // Create bright pass post-process
  72259. this._createBrightPassPostProcess(scene, ratio / 2);
  72260. // Create gaussian blur post-processes (down sampling blurs)
  72261. this._createBlurPostProcesses(scene, ratio / 4, 1);
  72262. // Create texture adder post-process
  72263. this._createTextureAdderPostProcess(scene, ratio);
  72264. // Create depth-of-field source post-process
  72265. 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);
  72266. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  72267. }
  72268. if (this._lensFlareEnabled) {
  72269. // Create lens flare post-process
  72270. this._createLensFlarePostProcess(scene, ratio);
  72271. // Create depth-of-field source post-process post lens-flare and disable it now
  72272. 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);
  72273. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  72274. }
  72275. if (this._hdrEnabled) {
  72276. // Create luminance
  72277. this._createLuminancePostProcesses(scene, this._floatTextureType);
  72278. // Create HDR
  72279. this._createHdrPostProcess(scene, ratio);
  72280. // Create depth-of-field source post-process post hdr and disable it now
  72281. 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);
  72282. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  72283. }
  72284. if (this._depthOfFieldEnabled) {
  72285. // Create gaussian blur used by depth-of-field
  72286. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  72287. // Create depth-of-field post-process
  72288. this._createDepthOfFieldPostProcess(scene, ratio);
  72289. }
  72290. if (this._motionBlurEnabled) {
  72291. // Create motion blur post-process
  72292. this._createMotionBlurPostProcess(scene, ratio);
  72293. }
  72294. if (this._cameras !== null) {
  72295. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  72296. }
  72297. };
  72298. // Down Sample X4 Post-Processs
  72299. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  72300. var _this = this;
  72301. var downSampleX4Offsets = new Array(32);
  72302. 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);
  72303. this.downSampleX4PostProcess.onApply = function (effect) {
  72304. var id = 0;
  72305. var width = _this.downSampleX4PostProcess.width;
  72306. var height = _this.downSampleX4PostProcess.height;
  72307. for (var i = -2; i < 2; i++) {
  72308. for (var j = -2; j < 2; j++) {
  72309. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  72310. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  72311. id += 2;
  72312. }
  72313. }
  72314. effect.setArray2("dsOffsets", downSampleX4Offsets);
  72315. };
  72316. // Add to pipeline
  72317. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  72318. };
  72319. // Brightpass Post-Process
  72320. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  72321. var _this = this;
  72322. var brightOffsets = new Array(8);
  72323. 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);
  72324. this.brightPassPostProcess.onApply = function (effect) {
  72325. var sU = (1.0 / _this.brightPassPostProcess.width);
  72326. var sV = (1.0 / _this.brightPassPostProcess.height);
  72327. brightOffsets[0] = -0.5 * sU;
  72328. brightOffsets[1] = 0.5 * sV;
  72329. brightOffsets[2] = 0.5 * sU;
  72330. brightOffsets[3] = 0.5 * sV;
  72331. brightOffsets[4] = -0.5 * sU;
  72332. brightOffsets[5] = -0.5 * sV;
  72333. brightOffsets[6] = 0.5 * sU;
  72334. brightOffsets[7] = -0.5 * sV;
  72335. effect.setArray2("dsOffsets", brightOffsets);
  72336. effect.setFloat("brightThreshold", _this.brightThreshold);
  72337. };
  72338. // Add to pipeline
  72339. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  72340. };
  72341. // Create blur H&V post-processes
  72342. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  72343. var _this = this;
  72344. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  72345. var engine = scene.getEngine();
  72346. 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);
  72347. 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);
  72348. blurX.onActivateObservable.add(function () {
  72349. var dw = blurX.width / engine.getRenderWidth();
  72350. blurX.kernel = _this[blurWidthKey] * dw;
  72351. });
  72352. blurY.onActivateObservable.add(function () {
  72353. var dw = blurY.height / engine.getRenderHeight();
  72354. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  72355. });
  72356. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  72357. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  72358. this.blurHPostProcesses.push(blurX);
  72359. this.blurVPostProcesses.push(blurY);
  72360. };
  72361. // Create texture adder post-process
  72362. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  72363. var _this = this;
  72364. 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);
  72365. this.textureAdderPostProcess.onApply = function (effect) {
  72366. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  72367. effect.setTexture("lensSampler", _this.lensTexture);
  72368. effect.setFloat("exposure", _this.exposure);
  72369. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  72370. };
  72371. // Add to pipeline
  72372. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  72373. };
  72374. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  72375. var _this = this;
  72376. var geometryRenderer = scene.enableGeometryBufferRenderer();
  72377. geometryRenderer.enablePosition = true;
  72378. var geometry = geometryRenderer.getGBuffer();
  72379. // Base post-process
  72380. 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));
  72381. var depthValues = BABYLON.Vector2.Zero();
  72382. this.volumetricLightPostProcess.onApply = function (effect) {
  72383. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  72384. var generator = _this.sourceLight.getShadowGenerator();
  72385. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  72386. effect.setTexture("positionSampler", geometry.textures[2]);
  72387. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  72388. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  72389. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  72390. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  72391. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  72392. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  72393. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  72394. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  72395. effect.setVector2("depthValues", depthValues);
  72396. }
  72397. };
  72398. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  72399. // Smooth
  72400. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  72401. // Merge
  72402. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  72403. this.volumetricLightMergePostProces.onApply = function (effect) {
  72404. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  72405. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  72406. };
  72407. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  72408. };
  72409. // Create luminance
  72410. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  72411. var _this = this;
  72412. // Create luminance
  72413. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  72414. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  72415. var offsets = [];
  72416. this.luminancePostProcess.onApply = function (effect) {
  72417. var sU = (1.0 / _this.luminancePostProcess.width);
  72418. var sV = (1.0 / _this.luminancePostProcess.height);
  72419. offsets[0] = -0.5 * sU;
  72420. offsets[1] = 0.5 * sV;
  72421. offsets[2] = 0.5 * sU;
  72422. offsets[3] = 0.5 * sV;
  72423. offsets[4] = -0.5 * sU;
  72424. offsets[5] = -0.5 * sV;
  72425. offsets[6] = 0.5 * sU;
  72426. offsets[7] = -0.5 * sV;
  72427. effect.setArray2("lumOffsets", offsets);
  72428. };
  72429. // Add to pipeline
  72430. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  72431. // Create down sample luminance
  72432. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  72433. var size = Math.pow(3, i);
  72434. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  72435. if (i === 0) {
  72436. defines += "#define FINAL_DOWN_SAMPLER";
  72437. }
  72438. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  72439. this.luminanceDownSamplePostProcesses.push(postProcess);
  72440. }
  72441. // Create callbacks and add effects
  72442. var lastLuminance = this.luminancePostProcess;
  72443. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  72444. var downSampleOffsets = new Array(18);
  72445. pp.onApply = function (effect) {
  72446. if (!lastLuminance) {
  72447. return;
  72448. }
  72449. var id = 0;
  72450. for (var x = -1; x < 2; x++) {
  72451. for (var y = -1; y < 2; y++) {
  72452. downSampleOffsets[id] = x / lastLuminance.width;
  72453. downSampleOffsets[id + 1] = y / lastLuminance.height;
  72454. id += 2;
  72455. }
  72456. }
  72457. effect.setArray2("dsOffsets", downSampleOffsets);
  72458. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  72459. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72460. lastLuminance = _this.luminancePostProcess;
  72461. }
  72462. else {
  72463. lastLuminance = pp;
  72464. }
  72465. };
  72466. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72467. pp.onAfterRender = function (effect) {
  72468. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  72469. 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);
  72470. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  72471. };
  72472. }
  72473. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  72474. });
  72475. };
  72476. // Create HDR post-process
  72477. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  72478. var _this = this;
  72479. 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);
  72480. var outputLiminance = 1;
  72481. var time = 0;
  72482. var lastTime = 0;
  72483. this.hdrPostProcess.onApply = function (effect) {
  72484. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  72485. time += scene.getEngine().getDeltaTime();
  72486. if (outputLiminance < 0) {
  72487. outputLiminance = _this._hdrCurrentLuminance;
  72488. }
  72489. else {
  72490. var dt = (lastTime - time) / 1000.0;
  72491. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  72492. outputLiminance += _this.hdrDecreaseRate * dt;
  72493. }
  72494. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  72495. outputLiminance -= _this.hdrIncreaseRate * dt;
  72496. }
  72497. else {
  72498. outputLiminance = _this._hdrCurrentLuminance;
  72499. }
  72500. }
  72501. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  72502. effect.setFloat("averageLuminance", outputLiminance);
  72503. lastTime = time;
  72504. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  72505. };
  72506. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  72507. };
  72508. // Create lens flare post-process
  72509. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  72510. var _this = this;
  72511. 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);
  72512. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  72513. this._createBlurPostProcesses(scene, ratio / 4, 2);
  72514. 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);
  72515. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  72516. var resolution = new BABYLON.Vector2(0, 0);
  72517. // Lens flare
  72518. this.lensFlarePostProcess.onApply = function (effect) {
  72519. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  72520. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  72521. effect.setFloat("strength", _this.lensFlareStrength);
  72522. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  72523. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  72524. // Shift
  72525. resolution.x = _this.lensFlarePostProcess.width;
  72526. resolution.y = _this.lensFlarePostProcess.height;
  72527. effect.setVector2("resolution", resolution);
  72528. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  72529. };
  72530. // Compose
  72531. 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);
  72532. 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);
  72533. this.lensFlareComposePostProcess.onApply = function (effect) {
  72534. if (!_this._scene.activeCamera) {
  72535. return;
  72536. }
  72537. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72538. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  72539. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  72540. // Lens start rotation matrix
  72541. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  72542. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  72543. 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));
  72544. camRot *= 4.0;
  72545. 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);
  72546. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  72547. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  72548. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  72549. };
  72550. };
  72551. // Create depth-of-field post-process
  72552. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  72553. var _this = this;
  72554. 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);
  72555. this.depthOfFieldPostProcess.onApply = function (effect) {
  72556. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72557. effect.setTexture("depthSampler", _this._getDepthTexture());
  72558. effect.setFloat("distance", _this.depthOfFieldDistance);
  72559. };
  72560. // Add to pipeline
  72561. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  72562. };
  72563. // Create motion blur post-process
  72564. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  72565. var _this = this;
  72566. 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);
  72567. var motionScale = 0;
  72568. var prevViewProjection = BABYLON.Matrix.Identity();
  72569. var invViewProjection = BABYLON.Matrix.Identity();
  72570. var viewProjection = BABYLON.Matrix.Identity();
  72571. var screenSize = BABYLON.Vector2.Zero();
  72572. this.motionBlurPostProcess.onApply = function (effect) {
  72573. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  72574. viewProjection.invertToRef(invViewProjection);
  72575. effect.setMatrix("inverseViewProjection", invViewProjection);
  72576. effect.setMatrix("prevViewProjection", prevViewProjection);
  72577. prevViewProjection = viewProjection;
  72578. screenSize.x = _this.motionBlurPostProcess.width;
  72579. screenSize.y = _this.motionBlurPostProcess.height;
  72580. effect.setVector2("screenSize", screenSize);
  72581. motionScale = scene.getEngine().getFps() / 60.0;
  72582. effect.setFloat("motionScale", motionScale);
  72583. effect.setFloat("motionStrength", _this.motionStrength);
  72584. effect.setTexture("depthSampler", _this._getDepthTexture());
  72585. };
  72586. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  72587. };
  72588. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  72589. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  72590. var renderer = this._scene.enableGeometryBufferRenderer();
  72591. return renderer.getGBuffer().textures[0];
  72592. }
  72593. return this._scene.enableDepthRenderer().getDepthMap();
  72594. };
  72595. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  72596. for (var i = 0; i < this._cameras.length; i++) {
  72597. var camera = this._cameras[i];
  72598. if (this.originalPostProcess) {
  72599. this.originalPostProcess.dispose(camera);
  72600. }
  72601. if (this.downSampleX4PostProcess) {
  72602. this.downSampleX4PostProcess.dispose(camera);
  72603. }
  72604. if (this.brightPassPostProcess) {
  72605. this.brightPassPostProcess.dispose(camera);
  72606. }
  72607. if (this.textureAdderPostProcess) {
  72608. this.textureAdderPostProcess.dispose(camera);
  72609. }
  72610. if (this.textureAdderFinalPostProcess) {
  72611. this.textureAdderFinalPostProcess.dispose(camera);
  72612. }
  72613. if (this.volumetricLightPostProcess) {
  72614. this.volumetricLightPostProcess.dispose(camera);
  72615. }
  72616. if (this.volumetricLightSmoothXPostProcess) {
  72617. this.volumetricLightSmoothXPostProcess.dispose(camera);
  72618. }
  72619. if (this.volumetricLightSmoothYPostProcess) {
  72620. this.volumetricLightSmoothYPostProcess.dispose(camera);
  72621. }
  72622. if (this.volumetricLightMergePostProces) {
  72623. this.volumetricLightMergePostProces.dispose(camera);
  72624. }
  72625. if (this.volumetricLightFinalPostProcess) {
  72626. this.volumetricLightFinalPostProcess.dispose(camera);
  72627. }
  72628. if (this.lensFlarePostProcess) {
  72629. this.lensFlarePostProcess.dispose(camera);
  72630. }
  72631. if (this.lensFlareComposePostProcess) {
  72632. this.lensFlareComposePostProcess.dispose(camera);
  72633. }
  72634. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  72635. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  72636. }
  72637. if (this.luminancePostProcess) {
  72638. this.luminancePostProcess.dispose(camera);
  72639. }
  72640. if (this.hdrPostProcess) {
  72641. this.hdrPostProcess.dispose(camera);
  72642. }
  72643. if (this.hdrFinalPostProcess) {
  72644. this.hdrFinalPostProcess.dispose(camera);
  72645. }
  72646. if (this.depthOfFieldPostProcess) {
  72647. this.depthOfFieldPostProcess.dispose(camera);
  72648. }
  72649. if (this.motionBlurPostProcess) {
  72650. this.motionBlurPostProcess.dispose(camera);
  72651. }
  72652. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  72653. this.blurHPostProcesses[j].dispose(camera);
  72654. }
  72655. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  72656. this.blurVPostProcesses[j].dispose(camera);
  72657. }
  72658. }
  72659. this.originalPostProcess = null;
  72660. this.downSampleX4PostProcess = null;
  72661. this.brightPassPostProcess = null;
  72662. this.textureAdderPostProcess = null;
  72663. this.textureAdderFinalPostProcess = null;
  72664. this.volumetricLightPostProcess = null;
  72665. this.volumetricLightSmoothXPostProcess = null;
  72666. this.volumetricLightSmoothYPostProcess = null;
  72667. this.volumetricLightMergePostProces = null;
  72668. this.volumetricLightFinalPostProcess = null;
  72669. this.lensFlarePostProcess = null;
  72670. this.lensFlareComposePostProcess = null;
  72671. this.luminancePostProcess = null;
  72672. this.hdrPostProcess = null;
  72673. this.hdrFinalPostProcess = null;
  72674. this.depthOfFieldPostProcess = null;
  72675. this.motionBlurPostProcess = null;
  72676. this.luminanceDownSamplePostProcesses = [];
  72677. this.blurHPostProcesses = [];
  72678. this.blurVPostProcesses = [];
  72679. };
  72680. // Dispose
  72681. StandardRenderingPipeline.prototype.dispose = function () {
  72682. this._disposePostProcesses();
  72683. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  72684. _super.prototype.dispose.call(this);
  72685. };
  72686. // Serialize rendering pipeline
  72687. StandardRenderingPipeline.prototype.serialize = function () {
  72688. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72689. serializationObject.customType = "StandardRenderingPipeline";
  72690. return serializationObject;
  72691. };
  72692. /**
  72693. * Static members
  72694. */
  72695. // Parse serialized pipeline
  72696. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  72697. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  72698. };
  72699. // Luminance steps
  72700. StandardRenderingPipeline.LuminanceSteps = 6;
  72701. __decorate([
  72702. BABYLON.serialize()
  72703. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  72704. __decorate([
  72705. BABYLON.serialize()
  72706. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  72707. __decorate([
  72708. BABYLON.serialize()
  72709. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  72710. __decorate([
  72711. BABYLON.serialize()
  72712. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  72713. __decorate([
  72714. BABYLON.serializeAsTexture("lensTexture")
  72715. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  72716. __decorate([
  72717. BABYLON.serialize()
  72718. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  72719. __decorate([
  72720. BABYLON.serialize()
  72721. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  72722. __decorate([
  72723. BABYLON.serialize()
  72724. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  72725. __decorate([
  72726. BABYLON.serialize()
  72727. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  72728. __decorate([
  72729. BABYLON.serialize()
  72730. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  72731. __decorate([
  72732. BABYLON.serialize()
  72733. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  72734. __decorate([
  72735. BABYLON.serializeAsTexture("lensColorTexture")
  72736. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  72737. __decorate([
  72738. BABYLON.serialize()
  72739. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  72740. __decorate([
  72741. BABYLON.serialize()
  72742. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  72743. __decorate([
  72744. BABYLON.serialize()
  72745. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  72746. __decorate([
  72747. BABYLON.serialize()
  72748. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  72749. __decorate([
  72750. BABYLON.serializeAsTexture("lensStarTexture")
  72751. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  72752. __decorate([
  72753. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  72754. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  72755. __decorate([
  72756. BABYLON.serialize()
  72757. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  72758. __decorate([
  72759. BABYLON.serialize()
  72760. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  72761. __decorate([
  72762. BABYLON.serialize()
  72763. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  72764. __decorate([
  72765. BABYLON.serialize()
  72766. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  72767. __decorate([
  72768. BABYLON.serialize()
  72769. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  72770. __decorate([
  72771. BABYLON.serialize()
  72772. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  72773. __decorate([
  72774. BABYLON.serialize()
  72775. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  72776. __decorate([
  72777. BABYLON.serialize()
  72778. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  72779. __decorate([
  72780. BABYLON.serialize()
  72781. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  72782. __decorate([
  72783. BABYLON.serialize()
  72784. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  72785. __decorate([
  72786. BABYLON.serialize()
  72787. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  72788. __decorate([
  72789. BABYLON.serialize()
  72790. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  72791. return StandardRenderingPipeline;
  72792. }(BABYLON.PostProcessRenderPipeline));
  72793. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  72794. })(BABYLON || (BABYLON = {}));
  72795. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  72796. "use strict";
  72797. var BABYLON;
  72798. (function (BABYLON) {
  72799. var FxaaPostProcess = /** @class */ (function (_super) {
  72800. __extends(FxaaPostProcess, _super);
  72801. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72802. if (camera === void 0) { camera = null; }
  72803. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72804. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  72805. _this.onApplyObservable.add(function (effect) {
  72806. var texelSize = _this.texelSize;
  72807. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  72808. });
  72809. return _this;
  72810. }
  72811. return FxaaPostProcess;
  72812. }(BABYLON.PostProcess));
  72813. BABYLON.FxaaPostProcess = FxaaPostProcess;
  72814. })(BABYLON || (BABYLON = {}));
  72815. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  72816. "use strict";
  72817. var BABYLON;
  72818. (function (BABYLON) {
  72819. /**
  72820. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  72821. */
  72822. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  72823. __extends(ChromaticAberrationPostProcess, _super);
  72824. /**
  72825. * Creates a new instance ChromaticAberrationPostProcess
  72826. * @param name The name of the effect.
  72827. * @param screenWidth The width of the screen to apply the effect on.
  72828. * @param screenHeight The height of the screen to apply the effect on.
  72829. * @param options The required width/height ratio to downsize to before computing the render pass.
  72830. * @param camera The camera to apply the render pass to.
  72831. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72832. * @param engine The engine which the post process will be applied. (default: current engine)
  72833. * @param reusable If the post process can be reused on the same frame. (default: false)
  72834. * @param textureType Type of textures used when performing the post process. (default: 0)
  72835. * @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)
  72836. */
  72837. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72838. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72839. if (blockCompilation === void 0) { blockCompilation = false; }
  72840. 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;
  72841. /**
  72842. * The amount of seperation of rgb channels (default: 30)
  72843. */
  72844. _this.aberrationAmount = 30;
  72845. /**
  72846. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  72847. */
  72848. _this.radialIntensity = 0;
  72849. /**
  72850. * 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))
  72851. */
  72852. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  72853. /**
  72854. * 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))
  72855. */
  72856. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  72857. _this.onApplyObservable.add(function (effect) {
  72858. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  72859. effect.setFloat('screen_width', screenWidth);
  72860. effect.setFloat('screen_height', screenHeight);
  72861. effect.setFloat('radialIntensity', _this.radialIntensity);
  72862. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  72863. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  72864. });
  72865. return _this;
  72866. }
  72867. return ChromaticAberrationPostProcess;
  72868. }(BABYLON.PostProcess));
  72869. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  72870. })(BABYLON || (BABYLON = {}));
  72871. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  72872. "use strict";
  72873. var BABYLON;
  72874. (function (BABYLON) {
  72875. /**
  72876. * The GrainPostProcess adds noise to the image at mid luminance levels
  72877. */
  72878. var GrainPostProcess = /** @class */ (function (_super) {
  72879. __extends(GrainPostProcess, _super);
  72880. /**
  72881. * Creates a new instance of @see GrainPostProcess
  72882. * @param name The name of the effect.
  72883. * @param options The required width/height ratio to downsize to before computing the render pass.
  72884. * @param camera The camera to apply the render pass to.
  72885. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72886. * @param engine The engine which the post process will be applied. (default: current engine)
  72887. * @param reusable If the post process can be reused on the same frame. (default: false)
  72888. * @param textureType Type of textures used when performing the post process. (default: 0)
  72889. * @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)
  72890. */
  72891. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72892. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72893. if (blockCompilation === void 0) { blockCompilation = false; }
  72894. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72895. /**
  72896. * The intensity of the grain added (default: 30)
  72897. */
  72898. _this.intensity = 30;
  72899. /**
  72900. * If the grain should be randomized on every frame
  72901. */
  72902. _this.animated = false;
  72903. _this.onApplyObservable.add(function (effect) {
  72904. effect.setFloat('intensity', _this.intensity);
  72905. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  72906. });
  72907. return _this;
  72908. }
  72909. return GrainPostProcess;
  72910. }(BABYLON.PostProcess));
  72911. BABYLON.GrainPostProcess = GrainPostProcess;
  72912. })(BABYLON || (BABYLON = {}));
  72913. //# sourceMappingURL=babylon.grainPostProcess.js.map
  72914. "use strict";
  72915. var BABYLON;
  72916. (function (BABYLON) {
  72917. /**
  72918. * The SharpenPostProcess applies a sharpen kernel to every pixel
  72919. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  72920. */
  72921. var SharpenPostProcess = /** @class */ (function (_super) {
  72922. __extends(SharpenPostProcess, _super);
  72923. /**
  72924. * Creates a new instance ConvolutionPostProcess
  72925. * @param name The name of the effect.
  72926. * @param options The required width/height ratio to downsize to before computing the render pass.
  72927. * @param camera The camera to apply the render pass to.
  72928. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72929. * @param engine The engine which the post process will be applied. (default: current engine)
  72930. * @param reusable If the post process can be reused on the same frame. (default: false)
  72931. * @param textureType Type of textures used when performing the post process. (default: 0)
  72932. * @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)
  72933. */
  72934. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72935. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72936. if (blockCompilation === void 0) { blockCompilation = false; }
  72937. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72938. /**
  72939. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  72940. */
  72941. _this.colorAmount = 1.0;
  72942. /**
  72943. * How much sharpness should be applied (default: 0.3)
  72944. */
  72945. _this.edgeAmount = 0.3;
  72946. _this.onApply = function (effect) {
  72947. effect.setFloat2("screenSize", _this.width, _this.height);
  72948. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  72949. };
  72950. return _this;
  72951. }
  72952. return SharpenPostProcess;
  72953. }(BABYLON.PostProcess));
  72954. BABYLON.SharpenPostProcess = SharpenPostProcess;
  72955. })(BABYLON || (BABYLON = {}));
  72956. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  72957. "use strict";
  72958. var BABYLON;
  72959. (function (BABYLON) {
  72960. /**
  72961. * The Blur Post Process which blurs an image based on a kernel and direction.
  72962. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  72963. */
  72964. var BlurPostProcess = /** @class */ (function (_super) {
  72965. __extends(BlurPostProcess, _super);
  72966. /**
  72967. * Creates a new instance BlurPostProcess
  72968. * @param name The name of the effect.
  72969. * @param direction The direction in which to blur the image.
  72970. * @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.
  72971. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  72972. * @param camera The camera to apply the render pass to.
  72973. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72974. * @param engine The engine which the post process will be applied. (default: current engine)
  72975. * @param reusable If the post process can be reused on the same frame. (default: false)
  72976. * @param textureType Type of textures used when performing the post process. (default: 0)
  72977. * @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)
  72978. */
  72979. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  72980. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72981. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72982. if (defines === void 0) { defines = ""; }
  72983. if (blockCompilation === void 0) { blockCompilation = false; }
  72984. 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;
  72985. _this.direction = direction;
  72986. _this.blockCompilation = blockCompilation;
  72987. _this._packedFloat = false;
  72988. _this._staticDefines = "";
  72989. _this._staticDefines = defines;
  72990. _this.onApplyObservable.add(function (effect) {
  72991. if (_this._outputTexture) {
  72992. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  72993. }
  72994. else {
  72995. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  72996. }
  72997. });
  72998. _this.kernel = kernel;
  72999. return _this;
  73000. }
  73001. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  73002. /**
  73003. * Gets the length in pixels of the blur sample region
  73004. */
  73005. get: function () {
  73006. return this._idealKernel;
  73007. },
  73008. /**
  73009. * Sets the length in pixels of the blur sample region
  73010. */
  73011. set: function (v) {
  73012. if (this._idealKernel === v) {
  73013. return;
  73014. }
  73015. v = Math.max(v, 1);
  73016. this._idealKernel = v;
  73017. this._kernel = this._nearestBestKernel(v);
  73018. if (!this.blockCompilation) {
  73019. this._updateParameters();
  73020. }
  73021. },
  73022. enumerable: true,
  73023. configurable: true
  73024. });
  73025. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  73026. /**
  73027. * Gets wether or not the blur is unpacking/repacking floats
  73028. */
  73029. get: function () {
  73030. return this._packedFloat;
  73031. },
  73032. /**
  73033. * Sets wether or not the blur needs to unpack/repack floats
  73034. */
  73035. set: function (v) {
  73036. if (this._packedFloat === v) {
  73037. return;
  73038. }
  73039. this._packedFloat = v;
  73040. if (!this.blockCompilation) {
  73041. this._updateParameters();
  73042. }
  73043. },
  73044. enumerable: true,
  73045. configurable: true
  73046. });
  73047. /**
  73048. * Updates the effect with the current post process compile time values and recompiles the shader.
  73049. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73050. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73051. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73052. * @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
  73053. * @param onCompiled Called when the shader has been compiled.
  73054. * @param onError Called if there is an error when compiling a shader.
  73055. */
  73056. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73057. if (defines === void 0) { defines = null; }
  73058. if (uniforms === void 0) { uniforms = null; }
  73059. if (samplers === void 0) { samplers = null; }
  73060. this._updateParameters(onCompiled, onError);
  73061. };
  73062. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  73063. // Generate sampling offsets and weights
  73064. var N = this._kernel;
  73065. var centerIndex = (N - 1) / 2;
  73066. // Generate Gaussian sampling weights over kernel
  73067. var offsets = [];
  73068. var weights = [];
  73069. var totalWeight = 0;
  73070. for (var i = 0; i < N; i++) {
  73071. var u = i / (N - 1);
  73072. var w = this._gaussianWeight(u * 2.0 - 1);
  73073. offsets[i] = (i - centerIndex);
  73074. weights[i] = w;
  73075. totalWeight += w;
  73076. }
  73077. // Normalize weights
  73078. for (var i = 0; i < weights.length; i++) {
  73079. weights[i] /= totalWeight;
  73080. }
  73081. // Optimize: combine samples to take advantage of hardware linear sampling
  73082. // Walk from left to center, combining pairs (symmetrically)
  73083. var linearSamplingWeights = [];
  73084. var linearSamplingOffsets = [];
  73085. var linearSamplingMap = [];
  73086. for (var i = 0; i <= centerIndex; i += 2) {
  73087. var j = Math.min(i + 1, Math.floor(centerIndex));
  73088. var singleCenterSample = i === j;
  73089. if (singleCenterSample) {
  73090. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73091. }
  73092. else {
  73093. var sharedCell = j === centerIndex;
  73094. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  73095. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  73096. if (offsetLinear === 0) {
  73097. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73098. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  73099. }
  73100. else {
  73101. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  73102. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  73103. }
  73104. }
  73105. }
  73106. for (var i = 0; i < linearSamplingMap.length; i++) {
  73107. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  73108. linearSamplingWeights[i] = linearSamplingMap[i].w;
  73109. }
  73110. // Replace with optimized
  73111. offsets = linearSamplingOffsets;
  73112. weights = linearSamplingWeights;
  73113. // Generate shaders
  73114. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  73115. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  73116. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  73117. var defines = "";
  73118. defines += this._staticDefines;
  73119. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  73120. if (this._staticDefines.indexOf("DOF") != -1) {
  73121. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  73122. varyingCount--;
  73123. }
  73124. for (var i = 0; i < varyingCount; i++) {
  73125. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  73126. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  73127. }
  73128. var depCount = 0;
  73129. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  73130. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  73131. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  73132. depCount++;
  73133. }
  73134. if (this.packedFloat) {
  73135. defines += "#define PACKEDFLOAT 1";
  73136. }
  73137. this.blockCompilation = false;
  73138. _super.prototype.updateEffect.call(this, defines, null, null, {
  73139. varyingCount: varyingCount,
  73140. depCount: depCount
  73141. }, onCompiled, onError);
  73142. };
  73143. /**
  73144. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  73145. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  73146. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  73147. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  73148. * The gaps between physical kernels are compensated for in the weighting of the samples
  73149. * @param idealKernel Ideal blur kernel.
  73150. * @return Nearest best kernel.
  73151. */
  73152. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  73153. var v = Math.round(idealKernel);
  73154. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  73155. var k = _a[_i];
  73156. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  73157. return Math.max(k, 3);
  73158. }
  73159. }
  73160. return Math.max(v, 3);
  73161. };
  73162. /**
  73163. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  73164. * @param x The point on the Gaussian distribution to sample.
  73165. * @return the value of the Gaussian function at x.
  73166. */
  73167. BlurPostProcess.prototype._gaussianWeight = function (x) {
  73168. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  73169. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  73170. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  73171. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  73172. // truncated at around 1.3% of peak strength.
  73173. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  73174. var sigma = (1 / 3);
  73175. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  73176. var exponent = -((x * x) / (2.0 * sigma * sigma));
  73177. var weight = (1.0 / denominator) * Math.exp(exponent);
  73178. return weight;
  73179. };
  73180. /**
  73181. * Generates a string that can be used as a floating point number in GLSL.
  73182. * @param x Value to print.
  73183. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  73184. * @return GLSL float string.
  73185. */
  73186. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  73187. if (decimalFigures === void 0) { decimalFigures = 8; }
  73188. return x.toFixed(decimalFigures).replace(/0+$/, '');
  73189. };
  73190. return BlurPostProcess;
  73191. }(BABYLON.PostProcess));
  73192. BABYLON.BlurPostProcess = BlurPostProcess;
  73193. })(BABYLON || (BABYLON = {}));
  73194. //# sourceMappingURL=babylon.blurPostProcess.js.map
  73195. "use strict";
  73196. var BABYLON;
  73197. (function (BABYLON) {
  73198. /**
  73199. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  73200. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  73201. * based on samples that have a large difference in distance than the center pixel.
  73202. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73203. */
  73204. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  73205. __extends(DepthOfFieldBlurPostProcess, _super);
  73206. /**
  73207. * Creates a new instance CircleOfConfusionPostProcess
  73208. * @param name The name of the effect.
  73209. * @param scene The scene the effect belongs to.
  73210. * @param direction The direction the blur should be applied.
  73211. * @param kernel The size of the kernel used to blur.
  73212. * @param options The required width/height ratio to downsize to before computing the render pass.
  73213. * @param camera The camera to apply the render pass to.
  73214. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  73215. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  73216. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73217. * @param engine The engine which the post process will be applied. (default: current engine)
  73218. * @param reusable If the post process can be reused on the same frame. (default: false)
  73219. * @param textureType Type of textures used when performing the post process. (default: 0)
  73220. * @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)
  73221. */
  73222. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  73223. if (imageToBlur === void 0) { imageToBlur = null; }
  73224. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73225. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73226. if (blockCompilation === void 0) { blockCompilation = false; }
  73227. 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;
  73228. _this.direction = direction;
  73229. _this.onApplyObservable.add(function (effect) {
  73230. if (imageToBlur != null) {
  73231. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  73232. }
  73233. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  73234. if (scene.activeCamera) {
  73235. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73236. }
  73237. });
  73238. return _this;
  73239. }
  73240. return DepthOfFieldBlurPostProcess;
  73241. }(BABYLON.BlurPostProcess));
  73242. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  73243. })(BABYLON || (BABYLON = {}));
  73244. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  73245. "use strict";
  73246. var BABYLON;
  73247. (function (BABYLON) {
  73248. /**
  73249. * Options to be set when merging outputs from the default pipeline.
  73250. */
  73251. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  73252. function DepthOfFieldMergePostProcessOptions() {
  73253. }
  73254. return DepthOfFieldMergePostProcessOptions;
  73255. }());
  73256. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  73257. /**
  73258. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73259. */
  73260. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  73261. __extends(DepthOfFieldMergePostProcess, _super);
  73262. /**
  73263. * Creates a new instance of DepthOfFieldMergePostProcess
  73264. * @param name The name of the effect.
  73265. * @param originalFromInput Post process which's input will be used for the merge.
  73266. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  73267. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  73268. * @param options The required width/height ratio to downsize to before computing the render pass.
  73269. * @param camera The camera to apply the render pass to.
  73270. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73271. * @param engine The engine which the post process will be applied. (default: current engine)
  73272. * @param reusable If the post process can be reused on the same frame. (default: false)
  73273. * @param textureType Type of textures used when performing the post process. (default: 0)
  73274. * @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)
  73275. */
  73276. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73277. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73278. if (blockCompilation === void 0) { blockCompilation = false; }
  73279. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73280. _this.blurSteps = blurSteps;
  73281. _this.onApplyObservable.add(function (effect) {
  73282. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73283. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  73284. blurSteps.forEach(function (step, index) {
  73285. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  73286. });
  73287. });
  73288. if (!blockCompilation) {
  73289. _this.updateEffect();
  73290. }
  73291. return _this;
  73292. }
  73293. /**
  73294. * Updates the effect with the current post process compile time values and recompiles the shader.
  73295. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73296. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73297. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73298. * @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
  73299. * @param onCompiled Called when the shader has been compiled.
  73300. * @param onError Called if there is an error when compiling a shader.
  73301. */
  73302. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73303. if (defines === void 0) { defines = null; }
  73304. if (uniforms === void 0) { uniforms = null; }
  73305. if (samplers === void 0) { samplers = null; }
  73306. if (!defines) {
  73307. defines = "";
  73308. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  73309. }
  73310. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  73311. };
  73312. return DepthOfFieldMergePostProcess;
  73313. }(BABYLON.PostProcess));
  73314. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  73315. })(BABYLON || (BABYLON = {}));
  73316. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  73317. "use strict";
  73318. var BABYLON;
  73319. (function (BABYLON) {
  73320. /**
  73321. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  73322. */
  73323. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  73324. __extends(CircleOfConfusionPostProcess, _super);
  73325. /**
  73326. * Creates a new instance CircleOfConfusionPostProcess
  73327. * @param name The name of the effect.
  73328. * @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.
  73329. * @param options The required width/height ratio to downsize to before computing the render pass.
  73330. * @param camera The camera to apply the render pass to.
  73331. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73332. * @param engine The engine which the post process will be applied. (default: current engine)
  73333. * @param reusable If the post process can be reused on the same frame. (default: false)
  73334. * @param textureType Type of textures used when performing the post process. (default: 0)
  73335. * @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)
  73336. */
  73337. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73338. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73339. if (blockCompilation === void 0) { blockCompilation = false; }
  73340. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73341. /**
  73342. * 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.
  73343. */
  73344. _this.lensSize = 50;
  73345. /**
  73346. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  73347. */
  73348. _this.fStop = 1.4;
  73349. /**
  73350. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  73351. */
  73352. _this.focusDistance = 2000;
  73353. /**
  73354. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  73355. */
  73356. _this.focalLength = 50;
  73357. _this._depthTexture = null;
  73358. _this._depthTexture = depthTexture;
  73359. _this.onApplyObservable.add(function (effect) {
  73360. if (!_this._depthTexture) {
  73361. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  73362. return;
  73363. }
  73364. effect.setTexture("depthSampler", _this._depthTexture);
  73365. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  73366. var aperture = _this.lensSize / _this.fStop;
  73367. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  73368. effect.setFloat('focusDistance', _this.focusDistance);
  73369. effect.setFloat('cocPrecalculation', cocPrecalculation);
  73370. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  73371. });
  73372. return _this;
  73373. }
  73374. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  73375. /**
  73376. * 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.
  73377. */
  73378. set: function (value) {
  73379. this._depthTexture = value;
  73380. },
  73381. enumerable: true,
  73382. configurable: true
  73383. });
  73384. return CircleOfConfusionPostProcess;
  73385. }(BABYLON.PostProcess));
  73386. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  73387. })(BABYLON || (BABYLON = {}));
  73388. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  73389. "use strict";
  73390. var BABYLON;
  73391. (function (BABYLON) {
  73392. /**
  73393. * Specifies the level of max blur that should be applied when using the depth of field effect
  73394. */
  73395. var DepthOfFieldEffectBlurLevel;
  73396. (function (DepthOfFieldEffectBlurLevel) {
  73397. /**
  73398. * Subtle blur
  73399. */
  73400. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  73401. /**
  73402. * Medium blur
  73403. */
  73404. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  73405. /**
  73406. * Large blur
  73407. */
  73408. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  73409. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  73410. ;
  73411. /**
  73412. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  73413. */
  73414. var DepthOfFieldEffect = /** @class */ (function (_super) {
  73415. __extends(DepthOfFieldEffect, _super);
  73416. /**
  73417. * Creates a new instance DepthOfFieldEffect
  73418. * @param scene The scene the effect belongs to.
  73419. * @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.
  73420. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  73421. * @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)
  73422. */
  73423. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  73424. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  73425. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  73426. if (blockCompilation === void 0) { blockCompilation = false; }
  73427. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  73428. return _this._effects;
  73429. }, true) || this;
  73430. /**
  73431. * Internal post processes in depth of field effect
  73432. */
  73433. _this._effects = [];
  73434. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  73435. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73436. // 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)
  73437. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  73438. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73439. _this._depthOfFieldBlurY = [];
  73440. _this._depthOfFieldBlurX = [];
  73441. var blurCount = 1;
  73442. var kernelSize = 15;
  73443. switch (blurLevel) {
  73444. case DepthOfFieldEffectBlurLevel.High: {
  73445. blurCount = 3;
  73446. kernelSize = 51;
  73447. break;
  73448. }
  73449. case DepthOfFieldEffectBlurLevel.Medium: {
  73450. blurCount = 2;
  73451. kernelSize = 31;
  73452. break;
  73453. }
  73454. default: {
  73455. kernelSize = 15;
  73456. blurCount = 1;
  73457. break;
  73458. }
  73459. }
  73460. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  73461. var ratio = 1.0;
  73462. for (var i = 0; i < blurCount; i++) {
  73463. 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);
  73464. blurY.autoClear = false;
  73465. ratio = 0.75 / Math.pow(2, i);
  73466. 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);
  73467. blurX.autoClear = false;
  73468. _this._depthOfFieldBlurY.push(blurY);
  73469. _this._depthOfFieldBlurX.push(blurX);
  73470. }
  73471. // Set all post processes on the effect.
  73472. _this._effects = [_this._circleOfConfusion];
  73473. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  73474. _this._effects.push(_this._depthOfFieldBlurY[i]);
  73475. _this._effects.push(_this._depthOfFieldBlurX[i]);
  73476. }
  73477. // Merge blurred images with original image based on circleOfConfusion
  73478. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73479. _this._dofMerge.autoClear = false;
  73480. _this._effects.push(_this._dofMerge);
  73481. return _this;
  73482. }
  73483. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  73484. get: function () {
  73485. return this._circleOfConfusion.focalLength;
  73486. },
  73487. /**
  73488. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  73489. */
  73490. set: function (value) {
  73491. this._circleOfConfusion.focalLength = value;
  73492. },
  73493. enumerable: true,
  73494. configurable: true
  73495. });
  73496. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  73497. get: function () {
  73498. return this._circleOfConfusion.fStop;
  73499. },
  73500. /**
  73501. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  73502. */
  73503. set: function (value) {
  73504. this._circleOfConfusion.fStop = value;
  73505. },
  73506. enumerable: true,
  73507. configurable: true
  73508. });
  73509. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  73510. get: function () {
  73511. return this._circleOfConfusion.focusDistance;
  73512. },
  73513. /**
  73514. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  73515. */
  73516. set: function (value) {
  73517. this._circleOfConfusion.focusDistance = value;
  73518. },
  73519. enumerable: true,
  73520. configurable: true
  73521. });
  73522. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  73523. get: function () {
  73524. return this._circleOfConfusion.lensSize;
  73525. },
  73526. /**
  73527. * 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.
  73528. */
  73529. set: function (value) {
  73530. this._circleOfConfusion.lensSize = value;
  73531. },
  73532. enumerable: true,
  73533. configurable: true
  73534. });
  73535. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  73536. /**
  73537. * 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.
  73538. */
  73539. set: function (value) {
  73540. this._circleOfConfusion.depthTexture = value;
  73541. },
  73542. enumerable: true,
  73543. configurable: true
  73544. });
  73545. /**
  73546. * Disposes each of the internal effects for a given camera.
  73547. * @param camera The camera to dispose the effect on.
  73548. */
  73549. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  73550. for (var effect in this._effects) {
  73551. this._effects[effect].dispose(camera);
  73552. }
  73553. };
  73554. /**
  73555. * Internal
  73556. */
  73557. DepthOfFieldEffect.prototype._updateEffects = function () {
  73558. for (var effect in this._effects) {
  73559. this._effects[effect].updateEffect();
  73560. }
  73561. };
  73562. /**
  73563. * Internal
  73564. * @returns if all the contained post processes are ready.
  73565. */
  73566. DepthOfFieldEffect.prototype._isReady = function () {
  73567. for (var effect in this._effects) {
  73568. if (!this._effects[effect].isReady()) {
  73569. return false;
  73570. }
  73571. }
  73572. return true;
  73573. };
  73574. return DepthOfFieldEffect;
  73575. }(BABYLON.PostProcessRenderEffect));
  73576. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  73577. })(BABYLON || (BABYLON = {}));
  73578. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  73579. "use strict";
  73580. var BABYLON;
  73581. (function (BABYLON) {
  73582. /**
  73583. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73584. */
  73585. var BloomMergePostProcess = /** @class */ (function (_super) {
  73586. __extends(BloomMergePostProcess, _super);
  73587. /**
  73588. * Creates a new instance of @see BloomMergePostProcess
  73589. * @param name The name of the effect.
  73590. * @param originalFromInput Post process which's input will be used for the merge.
  73591. * @param blurred Blurred highlights post process which's output will be used.
  73592. * @param weight Weight of the bloom to be added to the original input.
  73593. * @param options The required width/height ratio to downsize to before computing the render pass.
  73594. * @param camera The camera to apply the render pass to.
  73595. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73596. * @param engine The engine which the post process will be applied. (default: current engine)
  73597. * @param reusable If the post process can be reused on the same frame. (default: false)
  73598. * @param textureType Type of textures used when performing the post process. (default: 0)
  73599. * @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)
  73600. */
  73601. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73602. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73603. if (blockCompilation === void 0) { blockCompilation = false; }
  73604. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73605. _this.weight = weight;
  73606. _this.onApplyObservable.add(function (effect) {
  73607. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73608. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  73609. effect.setFloat("bloomWeight", _this.weight);
  73610. });
  73611. if (!blockCompilation) {
  73612. _this.updateEffect();
  73613. }
  73614. return _this;
  73615. }
  73616. return BloomMergePostProcess;
  73617. }(BABYLON.PostProcess));
  73618. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  73619. })(BABYLON || (BABYLON = {}));
  73620. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  73621. "use strict";
  73622. var BABYLON;
  73623. (function (BABYLON) {
  73624. /**
  73625. * 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.
  73626. */
  73627. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  73628. __extends(ExtractHighlightsPostProcess, _super);
  73629. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73630. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73631. if (blockCompilation === void 0) { blockCompilation = false; }
  73632. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73633. /**
  73634. * The luminance threshold, pixels below this value will be set to black.
  73635. */
  73636. _this.threshold = 0.9;
  73637. /**
  73638. * Internal
  73639. */
  73640. _this._exposure = 1;
  73641. /**
  73642. * Post process which has the input texture to be used when performing highlight extraction
  73643. */
  73644. _this._inputPostProcess = null;
  73645. _this.onApplyObservable.add(function (effect) {
  73646. if (_this._inputPostProcess) {
  73647. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  73648. }
  73649. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  73650. effect.setFloat('exposure', _this._exposure);
  73651. });
  73652. return _this;
  73653. }
  73654. return ExtractHighlightsPostProcess;
  73655. }(BABYLON.PostProcess));
  73656. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  73657. })(BABYLON || (BABYLON = {}));
  73658. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  73659. "use strict";
  73660. var BABYLON;
  73661. (function (BABYLON) {
  73662. /**
  73663. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  73664. */
  73665. var BloomEffect = /** @class */ (function (_super) {
  73666. __extends(BloomEffect, _super);
  73667. /**
  73668. * Creates a new instance of @see BloomEffect
  73669. * @param scene The scene the effect belongs to.
  73670. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  73671. * @param bloomKernel The size of the kernel to be used when applying the blur.
  73672. * @param bloomWeight The the strength of bloom.
  73673. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  73674. * @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)
  73675. */
  73676. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  73677. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  73678. if (blockCompilation === void 0) { blockCompilation = false; }
  73679. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  73680. return _this._effects;
  73681. }, true) || this;
  73682. _this.bloomScale = bloomScale;
  73683. /**
  73684. * Internal
  73685. */
  73686. _this._effects = [];
  73687. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73688. _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);
  73689. _this._blurX.alwaysForcePOT = true;
  73690. _this._blurX.autoClear = false;
  73691. _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);
  73692. _this._blurY.alwaysForcePOT = true;
  73693. _this._blurY.autoClear = false;
  73694. _this.kernel = bloomKernel;
  73695. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  73696. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73697. _this._merge.autoClear = false;
  73698. _this._effects.push(_this._merge);
  73699. return _this;
  73700. }
  73701. Object.defineProperty(BloomEffect.prototype, "threshold", {
  73702. /**
  73703. * The luminance threshold to find bright areas of the image to bloom.
  73704. */
  73705. get: function () {
  73706. return this._downscale.threshold;
  73707. },
  73708. set: function (value) {
  73709. this._downscale.threshold = value;
  73710. },
  73711. enumerable: true,
  73712. configurable: true
  73713. });
  73714. Object.defineProperty(BloomEffect.prototype, "weight", {
  73715. /**
  73716. * The strength of the bloom.
  73717. */
  73718. get: function () {
  73719. return this._merge.weight;
  73720. },
  73721. set: function (value) {
  73722. this._merge.weight = value;
  73723. },
  73724. enumerable: true,
  73725. configurable: true
  73726. });
  73727. Object.defineProperty(BloomEffect.prototype, "kernel", {
  73728. /**
  73729. * Specifies the size of the bloom blur kernel, relative to the final output size
  73730. */
  73731. get: function () {
  73732. return this._blurX.kernel / this.bloomScale;
  73733. },
  73734. set: function (value) {
  73735. this._blurX.kernel = value * this.bloomScale;
  73736. this._blurY.kernel = value * this.bloomScale;
  73737. },
  73738. enumerable: true,
  73739. configurable: true
  73740. });
  73741. /**
  73742. * Disposes each of the internal effects for a given camera.
  73743. * @param camera The camera to dispose the effect on.
  73744. */
  73745. BloomEffect.prototype.disposeEffects = function (camera) {
  73746. for (var effect in this._effects) {
  73747. this._effects[effect].dispose(camera);
  73748. }
  73749. };
  73750. /**
  73751. * Internal
  73752. */
  73753. BloomEffect.prototype._updateEffects = function () {
  73754. for (var effect in this._effects) {
  73755. this._effects[effect].updateEffect();
  73756. }
  73757. };
  73758. /**
  73759. * Internal
  73760. * @returns if all the contained post processes are ready.
  73761. */
  73762. BloomEffect.prototype._isReady = function () {
  73763. for (var effect in this._effects) {
  73764. if (!this._effects[effect].isReady()) {
  73765. return false;
  73766. }
  73767. }
  73768. return true;
  73769. };
  73770. return BloomEffect;
  73771. }(BABYLON.PostProcessRenderEffect));
  73772. BABYLON.BloomEffect = BloomEffect;
  73773. })(BABYLON || (BABYLON = {}));
  73774. //# sourceMappingURL=babylon.bloomEffect.js.map
  73775. "use strict";
  73776. var BABYLON;
  73777. (function (BABYLON) {
  73778. /**
  73779. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  73780. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  73781. */
  73782. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  73783. __extends(DefaultRenderingPipeline, _super);
  73784. /**
  73785. * @constructor
  73786. * @param {string} name - The rendering pipeline name
  73787. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73788. * @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)
  73789. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73790. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  73791. */
  73792. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  73793. if (automaticBuild === void 0) { automaticBuild = true; }
  73794. var _this = _super.call(this, scene.getEngine(), name) || this;
  73795. _this._originalCameras = [];
  73796. /**
  73797. * ID of the sharpen post process,
  73798. */
  73799. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  73800. /**
  73801. * ID of the image processing post process;
  73802. */
  73803. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  73804. /**
  73805. * ID of the Fast Approximate Anti-Aliasing post process;
  73806. */
  73807. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  73808. /**
  73809. * ID of the chromatic aberration post process,
  73810. */
  73811. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  73812. /**
  73813. * ID of the grain post process
  73814. */
  73815. _this.GrainPostProcessId = "GrainPostProcessEffect";
  73816. /**
  73817. * Animations which can be used to tweak settings over a period of time
  73818. */
  73819. _this.animations = [];
  73820. _this._imageProcessingConfigurationObserver = null;
  73821. // Values
  73822. _this._sharpenEnabled = false;
  73823. _this._bloomEnabled = false;
  73824. _this._depthOfFieldEnabled = false;
  73825. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  73826. _this._fxaaEnabled = false;
  73827. _this._imageProcessingEnabled = true;
  73828. _this._bloomScale = 0.5;
  73829. _this._chromaticAberrationEnabled = false;
  73830. _this._grainEnabled = false;
  73831. _this._buildAllowed = true;
  73832. _this._resizeObserver = null;
  73833. _this._hardwareScaleLevel = 1.0;
  73834. _this._bloomKernel = 64;
  73835. /**
  73836. * Specifies the weight of the bloom in the final rendering
  73837. */
  73838. _this._bloomWeight = 0.15;
  73839. /**
  73840. * Specifies the luma threshold for the area that will be blurred by the bloom
  73841. */
  73842. _this._bloomThreshold = 0.9;
  73843. _this._samples = 1;
  73844. _this._hasCleared = false;
  73845. _this._prevPostProcess = null;
  73846. _this._prevPrevPostProcess = null;
  73847. _this._cameras = cameras || [];
  73848. _this._originalCameras = _this._cameras.slice();
  73849. _this._buildAllowed = automaticBuild;
  73850. // Initialize
  73851. _this._scene = scene;
  73852. var caps = _this._scene.getEngine().getCaps();
  73853. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  73854. // Misc
  73855. if (_this._hdr) {
  73856. if (caps.textureHalfFloatRender) {
  73857. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73858. }
  73859. else if (caps.textureFloatRender) {
  73860. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73861. }
  73862. }
  73863. else {
  73864. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73865. }
  73866. // Attach
  73867. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73868. var engine = _this._scene.getEngine();
  73869. // Create post processes before hand so they can be modified before enabled.
  73870. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  73871. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73872. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  73873. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  73874. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  73875. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73876. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  73877. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73878. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  73879. _this._resizeObserver = engine.onResizeObservable.add(function () {
  73880. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  73881. _this.bloomKernel = _this.bloomKernel;
  73882. });
  73883. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  73884. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  73885. });
  73886. _this._buildPipeline();
  73887. return _this;
  73888. }
  73889. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  73890. get: function () {
  73891. return this._sharpenEnabled;
  73892. },
  73893. /**
  73894. * Enable or disable the sharpen process from the pipeline
  73895. */
  73896. set: function (enabled) {
  73897. if (this._sharpenEnabled === enabled) {
  73898. return;
  73899. }
  73900. this._sharpenEnabled = enabled;
  73901. this._buildPipeline();
  73902. },
  73903. enumerable: true,
  73904. configurable: true
  73905. });
  73906. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  73907. /**
  73908. * Specifies the size of the bloom blur kernel, relative to the final output size
  73909. */
  73910. get: function () {
  73911. return this._bloomKernel;
  73912. },
  73913. set: function (value) {
  73914. this._bloomKernel = value;
  73915. this.bloom.kernel = value / this._hardwareScaleLevel;
  73916. },
  73917. enumerable: true,
  73918. configurable: true
  73919. });
  73920. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  73921. get: function () {
  73922. return this._bloomWeight;
  73923. },
  73924. /**
  73925. * The strength of the bloom.
  73926. */
  73927. set: function (value) {
  73928. if (this._bloomWeight === value) {
  73929. return;
  73930. }
  73931. this.bloom.weight = value;
  73932. this._bloomWeight = value;
  73933. },
  73934. enumerable: true,
  73935. configurable: true
  73936. });
  73937. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  73938. get: function () {
  73939. return this._bloomThreshold;
  73940. },
  73941. /**
  73942. * The strength of the bloom.
  73943. */
  73944. set: function (value) {
  73945. if (this._bloomThreshold === value) {
  73946. return;
  73947. }
  73948. this.bloom.threshold = value;
  73949. this._bloomThreshold = value;
  73950. },
  73951. enumerable: true,
  73952. configurable: true
  73953. });
  73954. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  73955. get: function () {
  73956. return this._bloomScale;
  73957. },
  73958. /**
  73959. * The scale of the bloom, lower value will provide better performance.
  73960. */
  73961. set: function (value) {
  73962. if (this._bloomScale === value) {
  73963. return;
  73964. }
  73965. this._bloomScale = value;
  73966. // recreate bloom and dispose old as this setting is not dynamic
  73967. this._rebuildBloom();
  73968. this._buildPipeline();
  73969. },
  73970. enumerable: true,
  73971. configurable: true
  73972. });
  73973. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  73974. get: function () {
  73975. return this._bloomEnabled;
  73976. },
  73977. /**
  73978. * Enable or disable the bloom from the pipeline
  73979. */
  73980. set: function (enabled) {
  73981. if (this._bloomEnabled === enabled) {
  73982. return;
  73983. }
  73984. this._bloomEnabled = enabled;
  73985. this._buildPipeline();
  73986. },
  73987. enumerable: true,
  73988. configurable: true
  73989. });
  73990. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  73991. // recreate bloom and dispose old as this setting is not dynamic
  73992. var oldBloom = this.bloom;
  73993. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  73994. this.bloom.threshold = oldBloom.threshold;
  73995. for (var i = 0; i < this._cameras.length; i++) {
  73996. oldBloom.disposeEffects(this._cameras[i]);
  73997. }
  73998. };
  73999. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  74000. /**
  74001. * If the depth of field is enabled.
  74002. */
  74003. get: function () {
  74004. return this._depthOfFieldEnabled;
  74005. },
  74006. set: function (enabled) {
  74007. if (this._depthOfFieldEnabled === enabled) {
  74008. return;
  74009. }
  74010. this._depthOfFieldEnabled = enabled;
  74011. this._buildPipeline();
  74012. },
  74013. enumerable: true,
  74014. configurable: true
  74015. });
  74016. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  74017. /**
  74018. * Blur level of the depth of field effect. (Higher blur will effect performance)
  74019. */
  74020. get: function () {
  74021. return this._depthOfFieldBlurLevel;
  74022. },
  74023. set: function (value) {
  74024. if (this._depthOfFieldBlurLevel === value) {
  74025. return;
  74026. }
  74027. this._depthOfFieldBlurLevel = value;
  74028. // recreate dof and dispose old as this setting is not dynamic
  74029. var oldDof = this.depthOfField;
  74030. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  74031. this.depthOfField.focalLength = oldDof.focalLength;
  74032. this.depthOfField.focusDistance = oldDof.focusDistance;
  74033. this.depthOfField.fStop = oldDof.fStop;
  74034. this.depthOfField.lensSize = oldDof.lensSize;
  74035. for (var i = 0; i < this._cameras.length; i++) {
  74036. oldDof.disposeEffects(this._cameras[i]);
  74037. }
  74038. this._buildPipeline();
  74039. },
  74040. enumerable: true,
  74041. configurable: true
  74042. });
  74043. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  74044. get: function () {
  74045. return this._fxaaEnabled;
  74046. },
  74047. /**
  74048. * If the anti aliasing is enabled.
  74049. */
  74050. set: function (enabled) {
  74051. if (this._fxaaEnabled === enabled) {
  74052. return;
  74053. }
  74054. this._fxaaEnabled = enabled;
  74055. this._buildPipeline();
  74056. },
  74057. enumerable: true,
  74058. configurable: true
  74059. });
  74060. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  74061. get: function () {
  74062. return this._samples;
  74063. },
  74064. /**
  74065. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  74066. */
  74067. set: function (sampleCount) {
  74068. if (this._samples === sampleCount) {
  74069. return;
  74070. }
  74071. this._samples = sampleCount;
  74072. this._buildPipeline();
  74073. },
  74074. enumerable: true,
  74075. configurable: true
  74076. });
  74077. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  74078. get: function () {
  74079. return this._imageProcessingEnabled;
  74080. },
  74081. /**
  74082. * If image processing is enabled.
  74083. */
  74084. set: function (enabled) {
  74085. if (this._imageProcessingEnabled === enabled) {
  74086. return;
  74087. }
  74088. this._imageProcessingEnabled = enabled;
  74089. this._buildPipeline();
  74090. },
  74091. enumerable: true,
  74092. configurable: true
  74093. });
  74094. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  74095. get: function () {
  74096. return this._chromaticAberrationEnabled;
  74097. },
  74098. /**
  74099. * Enable or disable the chromaticAberration process from the pipeline
  74100. */
  74101. set: function (enabled) {
  74102. if (this._chromaticAberrationEnabled === enabled) {
  74103. return;
  74104. }
  74105. this._chromaticAberrationEnabled = enabled;
  74106. this._buildPipeline();
  74107. },
  74108. enumerable: true,
  74109. configurable: true
  74110. });
  74111. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  74112. get: function () {
  74113. return this._grainEnabled;
  74114. },
  74115. /**
  74116. * Enable or disable the grain process from the pipeline
  74117. */
  74118. set: function (enabled) {
  74119. if (this._grainEnabled === enabled) {
  74120. return;
  74121. }
  74122. this._grainEnabled = enabled;
  74123. this._buildPipeline();
  74124. },
  74125. enumerable: true,
  74126. configurable: true
  74127. });
  74128. /**
  74129. * Force the compilation of the entire pipeline.
  74130. */
  74131. DefaultRenderingPipeline.prototype.prepare = function () {
  74132. var previousState = this._buildAllowed;
  74133. this._buildAllowed = true;
  74134. this._buildPipeline();
  74135. this._buildAllowed = previousState;
  74136. };
  74137. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  74138. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  74139. if (this._hasCleared) {
  74140. postProcess.autoClear = false;
  74141. }
  74142. else {
  74143. postProcess.autoClear = true;
  74144. this._scene.autoClear = false;
  74145. this._hasCleared = true;
  74146. }
  74147. if (!skipTextureSharing) {
  74148. if (this._prevPrevPostProcess) {
  74149. postProcess.shareOutputWith(this._prevPrevPostProcess);
  74150. }
  74151. else {
  74152. postProcess.useOwnOutput();
  74153. }
  74154. if (this._prevPostProcess) {
  74155. this._prevPrevPostProcess = this._prevPostProcess;
  74156. }
  74157. this._prevPostProcess = postProcess;
  74158. }
  74159. };
  74160. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  74161. var _this = this;
  74162. if (!this._buildAllowed) {
  74163. return;
  74164. }
  74165. this._scene.autoClear = true;
  74166. var engine = this._scene.getEngine();
  74167. this._disposePostProcesses();
  74168. if (this._cameras !== null) {
  74169. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74170. // get back cameras to be used to reattach pipeline
  74171. this._cameras = this._originalCameras.slice();
  74172. }
  74173. this._reset();
  74174. this._prevPostProcess = null;
  74175. this._prevPrevPostProcess = null;
  74176. this._hasCleared = false;
  74177. if (this.depthOfFieldEnabled) {
  74178. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  74179. this.depthOfField.depthTexture = depthTexture;
  74180. if (!this.depthOfField._isReady()) {
  74181. this.depthOfField._updateEffects();
  74182. }
  74183. this.addEffect(this.depthOfField);
  74184. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  74185. }
  74186. if (this.bloomEnabled) {
  74187. if (!this.bloom._isReady()) {
  74188. this.bloom._updateEffects();
  74189. }
  74190. this.addEffect(this.bloom);
  74191. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  74192. }
  74193. if (this._imageProcessingEnabled) {
  74194. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  74195. if (this._hdr) {
  74196. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  74197. this._setAutoClearAndTextureSharing(this.imageProcessing);
  74198. }
  74199. else {
  74200. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  74201. }
  74202. }
  74203. if (this.sharpenEnabled) {
  74204. if (!this.sharpen.isReady()) {
  74205. this.sharpen.updateEffect();
  74206. }
  74207. this.addEffect(this._sharpenEffect);
  74208. this._setAutoClearAndTextureSharing(this.sharpen);
  74209. }
  74210. if (this.grainEnabled) {
  74211. if (!this.grain.isReady()) {
  74212. this.grain.updateEffect();
  74213. }
  74214. this.addEffect(this._grainEffect);
  74215. this._setAutoClearAndTextureSharing(this.grain);
  74216. }
  74217. if (this.chromaticAberrationEnabled) {
  74218. if (!this.chromaticAberration.isReady()) {
  74219. this.chromaticAberration.updateEffect();
  74220. }
  74221. this.addEffect(this._chromaticAberrationEffect);
  74222. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  74223. }
  74224. if (this.fxaaEnabled) {
  74225. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  74226. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  74227. this._setAutoClearAndTextureSharing(this.fxaa, true);
  74228. }
  74229. if (this._cameras !== null) {
  74230. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74231. }
  74232. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  74233. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  74234. }
  74235. };
  74236. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  74237. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  74238. for (var i = 0; i < this._cameras.length; i++) {
  74239. var camera = this._cameras[i];
  74240. if (this.imageProcessing) {
  74241. this.imageProcessing.dispose(camera);
  74242. }
  74243. if (this.fxaa) {
  74244. this.fxaa.dispose(camera);
  74245. }
  74246. // These are created in the constructor and should not be disposed on every pipeline change
  74247. if (disposeNonRecreated) {
  74248. if (this.sharpen) {
  74249. this.sharpen.dispose(camera);
  74250. }
  74251. if (this.depthOfField) {
  74252. this.depthOfField.disposeEffects(camera);
  74253. }
  74254. if (this.bloom) {
  74255. this.bloom.disposeEffects(camera);
  74256. }
  74257. if (this.chromaticAberration) {
  74258. this.chromaticAberration.dispose(camera);
  74259. }
  74260. if (this.grain) {
  74261. this.grain.dispose(camera);
  74262. }
  74263. }
  74264. }
  74265. this.imageProcessing = null;
  74266. this.fxaa = null;
  74267. if (disposeNonRecreated) {
  74268. this.sharpen = null;
  74269. this._sharpenEffect = null;
  74270. this.depthOfField = null;
  74271. this.bloom = null;
  74272. this.chromaticAberration = null;
  74273. this._chromaticAberrationEffect = null;
  74274. this.grain = null;
  74275. this._grainEffect = null;
  74276. }
  74277. };
  74278. /**
  74279. * Dispose of the pipeline and stop all post processes
  74280. */
  74281. DefaultRenderingPipeline.prototype.dispose = function () {
  74282. this._disposePostProcesses(true);
  74283. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74284. this._scene.autoClear = true;
  74285. if (this._resizeObserver) {
  74286. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  74287. this._resizeObserver = null;
  74288. }
  74289. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  74290. _super.prototype.dispose.call(this);
  74291. };
  74292. /**
  74293. * Serialize the rendering pipeline (Used when exporting)
  74294. * @returns the serialized object
  74295. */
  74296. DefaultRenderingPipeline.prototype.serialize = function () {
  74297. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74298. serializationObject.customType = "DefaultRenderingPipeline";
  74299. return serializationObject;
  74300. };
  74301. /**
  74302. * Parse the serialized pipeline
  74303. * @param source Source pipeline.
  74304. * @param scene The scene to load the pipeline to.
  74305. * @param rootUrl The URL of the serialized pipeline.
  74306. * @returns An instantiated pipeline from the serialized object.
  74307. */
  74308. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74309. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  74310. };
  74311. __decorate([
  74312. BABYLON.serialize()
  74313. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  74314. __decorate([
  74315. BABYLON.serialize()
  74316. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  74317. __decorate([
  74318. BABYLON.serialize()
  74319. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  74320. __decorate([
  74321. BABYLON.serialize()
  74322. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  74323. __decorate([
  74324. BABYLON.serialize()
  74325. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  74326. __decorate([
  74327. BABYLON.serialize()
  74328. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  74329. __decorate([
  74330. BABYLON.serialize()
  74331. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  74332. __decorate([
  74333. BABYLON.serialize()
  74334. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  74335. __decorate([
  74336. BABYLON.serialize()
  74337. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  74338. __decorate([
  74339. BABYLON.serialize()
  74340. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  74341. __decorate([
  74342. BABYLON.serialize()
  74343. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  74344. __decorate([
  74345. BABYLON.serialize()
  74346. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  74347. __decorate([
  74348. BABYLON.serialize()
  74349. ], DefaultRenderingPipeline.prototype, "samples", null);
  74350. __decorate([
  74351. BABYLON.serialize()
  74352. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  74353. __decorate([
  74354. BABYLON.serialize()
  74355. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  74356. __decorate([
  74357. BABYLON.serialize()
  74358. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  74359. return DefaultRenderingPipeline;
  74360. }(BABYLON.PostProcessRenderPipeline));
  74361. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  74362. })(BABYLON || (BABYLON = {}));
  74363. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  74364. "use strict";
  74365. var BABYLON;
  74366. (function (BABYLON) {
  74367. /**
  74368. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  74369. */
  74370. var GeometryBufferRenderer = /** @class */ (function () {
  74371. /**
  74372. * Creates a new G Buffer for the scene
  74373. * @param scene The scene the buffer belongs to
  74374. * @param ratio How big is the buffer related to the main canvas.
  74375. */
  74376. function GeometryBufferRenderer(scene, ratio) {
  74377. if (ratio === void 0) { ratio = 1; }
  74378. this._enablePosition = false;
  74379. this._scene = scene;
  74380. this._ratio = ratio;
  74381. // Render target
  74382. this._createRenderTargets();
  74383. }
  74384. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  74385. /**
  74386. * Set the render list (meshes to be rendered) used in the G buffer.
  74387. */
  74388. set: function (meshes) {
  74389. this._multiRenderTarget.renderList = meshes;
  74390. },
  74391. enumerable: true,
  74392. configurable: true
  74393. });
  74394. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  74395. /**
  74396. * Gets wether or not G buffer are supported by the running hardware.
  74397. * This requires draw buffer supports
  74398. */
  74399. get: function () {
  74400. return this._multiRenderTarget.isSupported;
  74401. },
  74402. enumerable: true,
  74403. configurable: true
  74404. });
  74405. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  74406. /**
  74407. * Gets wether or not position are enabled for the G buffer.
  74408. */
  74409. get: function () {
  74410. return this._enablePosition;
  74411. },
  74412. /**
  74413. * Sets wether or not position are enabled for the G buffer.
  74414. */
  74415. set: function (enable) {
  74416. this._enablePosition = enable;
  74417. this.dispose();
  74418. this._createRenderTargets();
  74419. },
  74420. enumerable: true,
  74421. configurable: true
  74422. });
  74423. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  74424. /**
  74425. * Gets the scene associated with the buffer.
  74426. */
  74427. get: function () {
  74428. return this._scene;
  74429. },
  74430. enumerable: true,
  74431. configurable: true
  74432. });
  74433. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  74434. /**
  74435. * Gets the ratio used by the buffer during its creation.
  74436. * How big is the buffer related to the main canvas.
  74437. */
  74438. get: function () {
  74439. return this._ratio;
  74440. },
  74441. enumerable: true,
  74442. configurable: true
  74443. });
  74444. /**
  74445. * Checks wether everything is ready to render a submesh to the G buffer.
  74446. * @param subMesh the submesh to check readiness for
  74447. * @param useInstances is the mesh drawn using instance or not
  74448. * @returns true if ready otherwise false
  74449. */
  74450. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  74451. var material = subMesh.getMaterial();
  74452. if (material && material.disableDepthWrite) {
  74453. return false;
  74454. }
  74455. var defines = [];
  74456. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74457. var mesh = subMesh.getMesh();
  74458. // Alpha test
  74459. if (material && material.needAlphaTesting()) {
  74460. defines.push("#define ALPHATEST");
  74461. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74462. attribs.push(BABYLON.VertexBuffer.UVKind);
  74463. defines.push("#define UV1");
  74464. }
  74465. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74466. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74467. defines.push("#define UV2");
  74468. }
  74469. }
  74470. // Buffers
  74471. if (this._enablePosition) {
  74472. defines.push("#define POSITION");
  74473. }
  74474. // Bones
  74475. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74476. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74477. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74478. if (mesh.numBoneInfluencers > 4) {
  74479. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74480. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74481. }
  74482. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74483. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74484. }
  74485. else {
  74486. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74487. }
  74488. // Instances
  74489. if (useInstances) {
  74490. defines.push("#define INSTANCES");
  74491. attribs.push("world0");
  74492. attribs.push("world1");
  74493. attribs.push("world2");
  74494. attribs.push("world3");
  74495. }
  74496. // Get correct effect
  74497. var join = defines.join("\n");
  74498. if (this._cachedDefines !== join) {
  74499. this._cachedDefines = join;
  74500. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  74501. }
  74502. return this._effect.isReady();
  74503. };
  74504. /**
  74505. * Gets the current underlying G Buffer.
  74506. * @returns the buffer
  74507. */
  74508. GeometryBufferRenderer.prototype.getGBuffer = function () {
  74509. return this._multiRenderTarget;
  74510. };
  74511. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  74512. /**
  74513. * Gets the number of samples used to render the buffer (anti aliasing).
  74514. */
  74515. get: function () {
  74516. return this._multiRenderTarget.samples;
  74517. },
  74518. /**
  74519. * Sets the number of samples used to render the buffer (anti aliasing).
  74520. */
  74521. set: function (value) {
  74522. this._multiRenderTarget.samples = value;
  74523. },
  74524. enumerable: true,
  74525. configurable: true
  74526. });
  74527. /**
  74528. * Disposes the renderer and frees up associated resources.
  74529. */
  74530. GeometryBufferRenderer.prototype.dispose = function () {
  74531. this.getGBuffer().dispose();
  74532. };
  74533. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  74534. var _this = this;
  74535. var engine = this._scene.getEngine();
  74536. var count = this._enablePosition ? 3 : 2;
  74537. 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 });
  74538. if (!this.isSupported) {
  74539. return;
  74540. }
  74541. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74542. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74543. this._multiRenderTarget.refreshRate = 1;
  74544. this._multiRenderTarget.renderParticles = false;
  74545. this._multiRenderTarget.renderList = null;
  74546. // set default depth value to 1.0 (far away)
  74547. this._multiRenderTarget.onClearObservable.add(function (engine) {
  74548. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  74549. });
  74550. // Custom render function
  74551. var renderSubMesh = function (subMesh) {
  74552. var mesh = subMesh.getRenderingMesh();
  74553. var scene = _this._scene;
  74554. var engine = scene.getEngine();
  74555. var material = subMesh.getMaterial();
  74556. if (!material) {
  74557. return;
  74558. }
  74559. // Culling
  74560. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74561. // Managing instances
  74562. var batch = mesh._getInstancesRenderList(subMesh._id);
  74563. if (batch.mustReturn) {
  74564. return;
  74565. }
  74566. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74567. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  74568. engine.enableEffect(_this._effect);
  74569. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74570. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74571. _this._effect.setMatrix("view", scene.getViewMatrix());
  74572. // Alpha test
  74573. if (material && material.needAlphaTesting()) {
  74574. var alphaTexture = material.getAlphaTestTexture();
  74575. if (alphaTexture) {
  74576. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74577. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74578. }
  74579. }
  74580. // Bones
  74581. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74582. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74583. }
  74584. // Draw
  74585. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74586. }
  74587. };
  74588. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74589. var index;
  74590. if (depthOnlySubMeshes.length) {
  74591. engine.setColorWrite(false);
  74592. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74593. renderSubMesh(depthOnlySubMeshes.data[index]);
  74594. }
  74595. engine.setColorWrite(true);
  74596. }
  74597. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74598. renderSubMesh(opaqueSubMeshes.data[index]);
  74599. }
  74600. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74601. renderSubMesh(alphaTestSubMeshes.data[index]);
  74602. }
  74603. };
  74604. };
  74605. return GeometryBufferRenderer;
  74606. }());
  74607. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  74608. })(BABYLON || (BABYLON = {}));
  74609. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  74610. "use strict";
  74611. var BABYLON;
  74612. (function (BABYLON) {
  74613. var RefractionPostProcess = /** @class */ (function (_super) {
  74614. __extends(RefractionPostProcess, _super);
  74615. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  74616. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  74617. _this.color = color;
  74618. _this.depth = depth;
  74619. _this.colorLevel = colorLevel;
  74620. _this._ownRefractionTexture = true;
  74621. _this.onActivateObservable.add(function (cam) {
  74622. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  74623. });
  74624. _this.onApplyObservable.add(function (effect) {
  74625. effect.setColor3("baseColor", _this.color);
  74626. effect.setFloat("depth", _this.depth);
  74627. effect.setFloat("colorLevel", _this.colorLevel);
  74628. effect.setTexture("refractionSampler", _this._refTexture);
  74629. });
  74630. return _this;
  74631. }
  74632. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  74633. /**
  74634. * Gets or sets the refraction texture
  74635. * Please note that you are responsible for disposing the texture if you set it manually
  74636. */
  74637. get: function () {
  74638. return this._refTexture;
  74639. },
  74640. set: function (value) {
  74641. if (this._refTexture && this._ownRefractionTexture) {
  74642. this._refTexture.dispose();
  74643. }
  74644. this._refTexture = value;
  74645. this._ownRefractionTexture = false;
  74646. },
  74647. enumerable: true,
  74648. configurable: true
  74649. });
  74650. // Methods
  74651. RefractionPostProcess.prototype.dispose = function (camera) {
  74652. if (this._refTexture && this._ownRefractionTexture) {
  74653. this._refTexture.dispose();
  74654. this._refTexture = null;
  74655. }
  74656. _super.prototype.dispose.call(this, camera);
  74657. };
  74658. return RefractionPostProcess;
  74659. }(BABYLON.PostProcess));
  74660. BABYLON.RefractionPostProcess = RefractionPostProcess;
  74661. })(BABYLON || (BABYLON = {}));
  74662. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  74663. "use strict";
  74664. var BABYLON;
  74665. (function (BABYLON) {
  74666. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  74667. __extends(BlackAndWhitePostProcess, _super);
  74668. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  74669. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  74670. _this.degree = 1;
  74671. _this.onApplyObservable.add(function (effect) {
  74672. effect.setFloat("degree", _this.degree);
  74673. });
  74674. return _this;
  74675. }
  74676. return BlackAndWhitePostProcess;
  74677. }(BABYLON.PostProcess));
  74678. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  74679. })(BABYLON || (BABYLON = {}));
  74680. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  74681. "use strict";
  74682. var BABYLON;
  74683. (function (BABYLON) {
  74684. /**
  74685. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  74686. * input texture to perform effects such as edge detection or sharpening
  74687. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74688. */
  74689. var ConvolutionPostProcess = /** @class */ (function (_super) {
  74690. __extends(ConvolutionPostProcess, _super);
  74691. /**
  74692. * Creates a new instance ConvolutionPostProcess
  74693. * @param name The name of the effect.
  74694. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  74695. * @param options The required width/height ratio to downsize to before computing the render pass.
  74696. * @param camera The camera to apply the render pass to.
  74697. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74698. * @param engine The engine which the post process will be applied. (default: current engine)
  74699. * @param reusable If the post process can be reused on the same frame. (default: false)
  74700. * @param textureType Type of textures used when performing the post process. (default: 0)
  74701. */
  74702. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  74703. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74704. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  74705. _this.kernel = kernel;
  74706. _this.onApply = function (effect) {
  74707. effect.setFloat2("screenSize", _this.width, _this.height);
  74708. effect.setArray("kernel", _this.kernel);
  74709. };
  74710. return _this;
  74711. }
  74712. // Statics
  74713. /**
  74714. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74715. */
  74716. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  74717. /**
  74718. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74719. */
  74720. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  74721. /**
  74722. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74723. */
  74724. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  74725. /**
  74726. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74727. */
  74728. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  74729. /**
  74730. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74731. */
  74732. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  74733. /**
  74734. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74735. */
  74736. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  74737. return ConvolutionPostProcess;
  74738. }(BABYLON.PostProcess));
  74739. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  74740. })(BABYLON || (BABYLON = {}));
  74741. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  74742. "use strict";
  74743. var BABYLON;
  74744. (function (BABYLON) {
  74745. var FilterPostProcess = /** @class */ (function (_super) {
  74746. __extends(FilterPostProcess, _super);
  74747. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  74748. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  74749. _this.kernelMatrix = kernelMatrix;
  74750. _this.onApply = function (effect) {
  74751. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  74752. };
  74753. return _this;
  74754. }
  74755. return FilterPostProcess;
  74756. }(BABYLON.PostProcess));
  74757. BABYLON.FilterPostProcess = FilterPostProcess;
  74758. })(BABYLON || (BABYLON = {}));
  74759. //# sourceMappingURL=babylon.filterPostProcess.js.map
  74760. "use strict";
  74761. var BABYLON;
  74762. (function (BABYLON) {
  74763. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  74764. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  74765. __extends(VolumetricLightScatteringPostProcess, _super);
  74766. /**
  74767. * @constructor
  74768. * @param {string} name - The post-process name
  74769. * @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)
  74770. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  74771. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  74772. * @param {number} samples - The post-process quality, default 100
  74773. * @param {number} samplingMode - The post-process filtering mode
  74774. * @param {BABYLON.Engine} engine - The babylon engine
  74775. * @param {boolean} reusable - If the post-process is reusable
  74776. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  74777. */
  74778. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  74779. if (samples === void 0) { samples = 100; }
  74780. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74781. 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;
  74782. _this._screenCoordinates = BABYLON.Vector2.Zero();
  74783. /**
  74784. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  74785. */
  74786. _this.customMeshPosition = BABYLON.Vector3.Zero();
  74787. /**
  74788. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  74789. */
  74790. _this.useCustomMeshPosition = false;
  74791. /**
  74792. * If the post-process should inverse the light scattering direction
  74793. */
  74794. _this.invert = true;
  74795. /**
  74796. * Array containing the excluded meshes not rendered in the internal pass
  74797. */
  74798. _this.excludedMeshes = new Array();
  74799. /**
  74800. * Controls the overall intensity of the post-process
  74801. */
  74802. _this.exposure = 0.3;
  74803. /**
  74804. * Dissipates each sample's contribution in range [0, 1]
  74805. */
  74806. _this.decay = 0.96815;
  74807. /**
  74808. * Controls the overall intensity of each sample
  74809. */
  74810. _this.weight = 0.58767;
  74811. /**
  74812. * Controls the density of each sample
  74813. */
  74814. _this.density = 0.926;
  74815. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  74816. engine = scene.getEngine();
  74817. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  74818. // Configure mesh
  74819. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  74820. // Configure
  74821. _this._createPass(scene, ratio.passRatio || ratio);
  74822. _this.onActivate = function (camera) {
  74823. if (!_this.isSupported) {
  74824. _this.dispose(camera);
  74825. }
  74826. _this.onActivate = null;
  74827. };
  74828. _this.onApplyObservable.add(function (effect) {
  74829. _this._updateMeshScreenCoordinates(scene);
  74830. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  74831. effect.setFloat("exposure", _this.exposure);
  74832. effect.setFloat("decay", _this.decay);
  74833. effect.setFloat("weight", _this.weight);
  74834. effect.setFloat("density", _this.density);
  74835. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  74836. });
  74837. return _this;
  74838. }
  74839. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  74840. get: function () {
  74841. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  74842. return false;
  74843. },
  74844. set: function (useDiffuseColor) {
  74845. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  74846. },
  74847. enumerable: true,
  74848. configurable: true
  74849. });
  74850. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  74851. return "VolumetricLightScatteringPostProcess";
  74852. };
  74853. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  74854. var mesh = subMesh.getMesh();
  74855. // Render this.mesh as default
  74856. if (mesh === this.mesh && mesh.material) {
  74857. return mesh.material.isReady(mesh);
  74858. }
  74859. var defines = [];
  74860. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74861. var material = subMesh.getMaterial();
  74862. // Alpha test
  74863. if (material) {
  74864. if (material.needAlphaTesting()) {
  74865. defines.push("#define ALPHATEST");
  74866. }
  74867. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74868. attribs.push(BABYLON.VertexBuffer.UVKind);
  74869. defines.push("#define UV1");
  74870. }
  74871. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74872. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74873. defines.push("#define UV2");
  74874. }
  74875. }
  74876. // Bones
  74877. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74878. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74879. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74880. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74881. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  74882. }
  74883. else {
  74884. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74885. }
  74886. // Instances
  74887. if (useInstances) {
  74888. defines.push("#define INSTANCES");
  74889. attribs.push("world0");
  74890. attribs.push("world1");
  74891. attribs.push("world2");
  74892. attribs.push("world3");
  74893. }
  74894. // Get correct effect
  74895. var join = defines.join("\n");
  74896. if (this._cachedDefines !== join) {
  74897. this._cachedDefines = join;
  74898. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  74899. }
  74900. return this._volumetricLightScatteringPass.isReady();
  74901. };
  74902. /**
  74903. * Sets the new light position for light scattering effect
  74904. * @param {BABYLON.Vector3} The new custom light position
  74905. */
  74906. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  74907. this.customMeshPosition = position;
  74908. };
  74909. /**
  74910. * Returns the light position for light scattering effect
  74911. * @return {BABYLON.Vector3} The custom light position
  74912. */
  74913. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  74914. return this.customMeshPosition;
  74915. };
  74916. /**
  74917. * Disposes the internal assets and detaches the post-process from the camera
  74918. */
  74919. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  74920. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  74921. if (rttIndex !== -1) {
  74922. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  74923. }
  74924. this._volumetricLightScatteringRTT.dispose();
  74925. _super.prototype.dispose.call(this, camera);
  74926. };
  74927. /**
  74928. * Returns the render target texture used by the post-process
  74929. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  74930. */
  74931. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  74932. return this._volumetricLightScatteringRTT;
  74933. };
  74934. // Private methods
  74935. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  74936. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  74937. return true;
  74938. }
  74939. return false;
  74940. };
  74941. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  74942. var _this = this;
  74943. var engine = scene.getEngine();
  74944. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74945. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74946. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74947. this._volumetricLightScatteringRTT.renderList = null;
  74948. this._volumetricLightScatteringRTT.renderParticles = false;
  74949. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  74950. var camera = this.getCamera();
  74951. if (camera) {
  74952. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  74953. }
  74954. else {
  74955. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  74956. }
  74957. // Custom render function for submeshes
  74958. var renderSubMesh = function (subMesh) {
  74959. var mesh = subMesh.getRenderingMesh();
  74960. if (_this._meshExcluded(mesh)) {
  74961. return;
  74962. }
  74963. var material = subMesh.getMaterial();
  74964. if (!material) {
  74965. return;
  74966. }
  74967. var scene = mesh.getScene();
  74968. var engine = scene.getEngine();
  74969. // Culling
  74970. engine.setState(material.backFaceCulling);
  74971. // Managing instances
  74972. var batch = mesh._getInstancesRenderList(subMesh._id);
  74973. if (batch.mustReturn) {
  74974. return;
  74975. }
  74976. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74977. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  74978. var effect = _this._volumetricLightScatteringPass;
  74979. if (mesh === _this.mesh) {
  74980. if (subMesh.effect) {
  74981. effect = subMesh.effect;
  74982. }
  74983. else {
  74984. effect = material.getEffect();
  74985. }
  74986. }
  74987. engine.enableEffect(effect);
  74988. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  74989. if (mesh === _this.mesh) {
  74990. material.bind(mesh.getWorldMatrix(), mesh);
  74991. }
  74992. else {
  74993. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  74994. // Alpha test
  74995. if (material && material.needAlphaTesting()) {
  74996. var alphaTexture = material.getAlphaTestTexture();
  74997. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  74998. if (alphaTexture) {
  74999. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75000. }
  75001. }
  75002. // Bones
  75003. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75004. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75005. }
  75006. }
  75007. // Draw
  75008. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  75009. }
  75010. };
  75011. // Render target texture callbacks
  75012. var savedSceneClearColor;
  75013. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  75014. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  75015. savedSceneClearColor = scene.clearColor;
  75016. scene.clearColor = sceneClearColor;
  75017. });
  75018. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  75019. scene.clearColor = savedSceneClearColor;
  75020. });
  75021. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75022. var engine = scene.getEngine();
  75023. var index;
  75024. if (depthOnlySubMeshes.length) {
  75025. engine.setColorWrite(false);
  75026. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75027. renderSubMesh(depthOnlySubMeshes.data[index]);
  75028. }
  75029. engine.setColorWrite(true);
  75030. }
  75031. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75032. renderSubMesh(opaqueSubMeshes.data[index]);
  75033. }
  75034. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75035. renderSubMesh(alphaTestSubMeshes.data[index]);
  75036. }
  75037. if (transparentSubMeshes.length) {
  75038. // Sort sub meshes
  75039. for (index = 0; index < transparentSubMeshes.length; index++) {
  75040. var submesh = transparentSubMeshes.data[index];
  75041. var boundingInfo = submesh.getBoundingInfo();
  75042. if (boundingInfo && scene.activeCamera) {
  75043. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  75044. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  75045. }
  75046. }
  75047. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  75048. sortedArray.sort(function (a, b) {
  75049. // Alpha index first
  75050. if (a._alphaIndex > b._alphaIndex) {
  75051. return 1;
  75052. }
  75053. if (a._alphaIndex < b._alphaIndex) {
  75054. return -1;
  75055. }
  75056. // Then distance to camera
  75057. if (a._distanceToCamera < b._distanceToCamera) {
  75058. return 1;
  75059. }
  75060. if (a._distanceToCamera > b._distanceToCamera) {
  75061. return -1;
  75062. }
  75063. return 0;
  75064. });
  75065. // Render sub meshes
  75066. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  75067. for (index = 0; index < sortedArray.length; index++) {
  75068. renderSubMesh(sortedArray[index]);
  75069. }
  75070. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75071. }
  75072. };
  75073. };
  75074. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  75075. var transform = scene.getTransformMatrix();
  75076. var meshPosition;
  75077. if (this.useCustomMeshPosition) {
  75078. meshPosition = this.customMeshPosition;
  75079. }
  75080. else if (this.attachedNode) {
  75081. meshPosition = this.attachedNode.position;
  75082. }
  75083. else {
  75084. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  75085. }
  75086. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  75087. this._screenCoordinates.x = pos.x / this._viewPort.width;
  75088. this._screenCoordinates.y = pos.y / this._viewPort.height;
  75089. if (this.invert)
  75090. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  75091. };
  75092. // Static methods
  75093. /**
  75094. * Creates a default mesh for the Volumeric Light Scattering post-process
  75095. * @param {string} The mesh name
  75096. * @param {BABYLON.Scene} The scene where to create the mesh
  75097. * @return {BABYLON.Mesh} the default mesh
  75098. */
  75099. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  75100. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  75101. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  75102. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  75103. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  75104. mesh.material = material;
  75105. return mesh;
  75106. };
  75107. __decorate([
  75108. BABYLON.serializeAsVector3()
  75109. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  75110. __decorate([
  75111. BABYLON.serialize()
  75112. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  75113. __decorate([
  75114. BABYLON.serialize()
  75115. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  75116. __decorate([
  75117. BABYLON.serializeAsMeshReference()
  75118. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  75119. __decorate([
  75120. BABYLON.serialize()
  75121. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  75122. __decorate([
  75123. BABYLON.serialize()
  75124. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  75125. __decorate([
  75126. BABYLON.serialize()
  75127. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  75128. __decorate([
  75129. BABYLON.serialize()
  75130. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  75131. __decorate([
  75132. BABYLON.serialize()
  75133. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  75134. return VolumetricLightScatteringPostProcess;
  75135. }(BABYLON.PostProcess));
  75136. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  75137. })(BABYLON || (BABYLON = {}));
  75138. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  75139. "use strict";
  75140. //
  75141. // This post-process allows the modification of rendered colors by using
  75142. // a 'look-up table' (LUT). This effect is also called Color Grading.
  75143. //
  75144. // The object needs to be provided an url to a texture containing the color
  75145. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  75146. // Use an image editing software to tweak the LUT to match your needs.
  75147. //
  75148. // For an example of a color LUT, see here:
  75149. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  75150. // For explanations on color grading, see here:
  75151. // http://udn.epicgames.com/Three/ColorGrading.html
  75152. //
  75153. var BABYLON;
  75154. (function (BABYLON) {
  75155. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  75156. __extends(ColorCorrectionPostProcess, _super);
  75157. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  75158. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  75159. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75160. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  75161. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75162. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75163. _this.onApply = function (effect) {
  75164. effect.setTexture("colorTable", _this._colorTableTexture);
  75165. };
  75166. return _this;
  75167. }
  75168. return ColorCorrectionPostProcess;
  75169. }(BABYLON.PostProcess));
  75170. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  75171. })(BABYLON || (BABYLON = {}));
  75172. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  75173. "use strict";
  75174. var BABYLON;
  75175. (function (BABYLON) {
  75176. var TonemappingOperator;
  75177. (function (TonemappingOperator) {
  75178. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  75179. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  75180. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  75181. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  75182. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  75183. ;
  75184. var TonemapPostProcess = /** @class */ (function (_super) {
  75185. __extends(TonemapPostProcess, _super);
  75186. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  75187. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75188. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75189. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  75190. _this._operator = _operator;
  75191. _this.exposureAdjustment = exposureAdjustment;
  75192. var defines = "#define ";
  75193. if (_this._operator === TonemappingOperator.Hable)
  75194. defines += "HABLE_TONEMAPPING";
  75195. else if (_this._operator === TonemappingOperator.Reinhard)
  75196. defines += "REINHARD_TONEMAPPING";
  75197. else if (_this._operator === TonemappingOperator.HejiDawson)
  75198. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  75199. else if (_this._operator === TonemappingOperator.Photographic)
  75200. defines += "PHOTOGRAPHIC_TONEMAPPING";
  75201. //sadly a second call to create the effect.
  75202. _this.updateEffect(defines);
  75203. _this.onApply = function (effect) {
  75204. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  75205. };
  75206. return _this;
  75207. }
  75208. return TonemapPostProcess;
  75209. }(BABYLON.PostProcess));
  75210. BABYLON.TonemapPostProcess = TonemapPostProcess;
  75211. })(BABYLON || (BABYLON = {}));
  75212. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  75213. "use strict";
  75214. var BABYLON;
  75215. (function (BABYLON) {
  75216. var DisplayPassPostProcess = /** @class */ (function (_super) {
  75217. __extends(DisplayPassPostProcess, _super);
  75218. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  75219. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  75220. }
  75221. return DisplayPassPostProcess;
  75222. }(BABYLON.PostProcess));
  75223. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  75224. })(BABYLON || (BABYLON = {}));
  75225. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  75226. "use strict";
  75227. var BABYLON;
  75228. (function (BABYLON) {
  75229. var HighlightsPostProcess = /** @class */ (function (_super) {
  75230. __extends(HighlightsPostProcess, _super);
  75231. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75232. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75233. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75234. }
  75235. return HighlightsPostProcess;
  75236. }(BABYLON.PostProcess));
  75237. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  75238. })(BABYLON || (BABYLON = {}));
  75239. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  75240. "use strict";
  75241. var BABYLON;
  75242. (function (BABYLON) {
  75243. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  75244. __extends(ImageProcessingPostProcess, _super);
  75245. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  75246. if (camera === void 0) { camera = null; }
  75247. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75248. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  75249. _this._fromLinearSpace = true;
  75250. /**
  75251. * Defines cache preventing GC.
  75252. */
  75253. _this._defines = {
  75254. IMAGEPROCESSING: false,
  75255. VIGNETTE: false,
  75256. VIGNETTEBLENDMODEMULTIPLY: false,
  75257. VIGNETTEBLENDMODEOPAQUE: false,
  75258. TONEMAPPING: false,
  75259. CONTRAST: false,
  75260. COLORCURVES: false,
  75261. COLORGRADING: false,
  75262. COLORGRADING3D: false,
  75263. FROMLINEARSPACE: false,
  75264. SAMPLER3DGREENDEPTH: false,
  75265. SAMPLER3DBGRMAP: false,
  75266. IMAGEPROCESSINGPOSTPROCESS: false,
  75267. EXPOSURE: false,
  75268. };
  75269. // Setup the configuration as forced by the constructor. This would then not force the
  75270. // scene materials output in linear space and let untouched the default forward pass.
  75271. if (imageProcessingConfiguration) {
  75272. imageProcessingConfiguration.applyByPostProcess = true;
  75273. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  75274. // This will cause the shader to be compiled
  75275. _this.fromLinearSpace = false;
  75276. }
  75277. else {
  75278. _this._attachImageProcessingConfiguration(null, true);
  75279. _this.imageProcessingConfiguration.applyByPostProcess = true;
  75280. }
  75281. _this.onApply = function (effect) {
  75282. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  75283. };
  75284. return _this;
  75285. }
  75286. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  75287. /**
  75288. * Gets the image processing configuration used either in this material.
  75289. */
  75290. get: function () {
  75291. return this._imageProcessingConfiguration;
  75292. },
  75293. /**
  75294. * Sets the Default image processing configuration used either in the this material.
  75295. *
  75296. * If sets to null, the scene one is in use.
  75297. */
  75298. set: function (value) {
  75299. this._attachImageProcessingConfiguration(value);
  75300. },
  75301. enumerable: true,
  75302. configurable: true
  75303. });
  75304. /**
  75305. * Attaches a new image processing configuration to the PBR Material.
  75306. * @param configuration
  75307. */
  75308. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  75309. var _this = this;
  75310. if (doNotBuild === void 0) { doNotBuild = false; }
  75311. if (configuration === this._imageProcessingConfiguration) {
  75312. return;
  75313. }
  75314. // Detaches observer.
  75315. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75316. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75317. }
  75318. // Pick the scene configuration if needed.
  75319. if (!configuration) {
  75320. var scene = null;
  75321. var engine = this.getEngine();
  75322. var camera = this.getCamera();
  75323. if (camera) {
  75324. scene = camera.getScene();
  75325. }
  75326. else if (engine && engine.scenes) {
  75327. var scenes = engine.scenes;
  75328. scene = scenes[scenes.length - 1];
  75329. }
  75330. else {
  75331. scene = BABYLON.Engine.LastCreatedScene;
  75332. }
  75333. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  75334. }
  75335. else {
  75336. this._imageProcessingConfiguration = configuration;
  75337. }
  75338. // Attaches observer.
  75339. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75340. _this._updateParameters();
  75341. });
  75342. // Ensure the effect will be rebuilt.
  75343. if (!doNotBuild) {
  75344. this._updateParameters();
  75345. }
  75346. };
  75347. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  75348. /**
  75349. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  75350. */
  75351. get: function () {
  75352. return this.imageProcessingConfiguration.colorCurves;
  75353. },
  75354. /**
  75355. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  75356. */
  75357. set: function (value) {
  75358. this.imageProcessingConfiguration.colorCurves = value;
  75359. },
  75360. enumerable: true,
  75361. configurable: true
  75362. });
  75363. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  75364. /**
  75365. * Gets wether the color curves effect is enabled.
  75366. */
  75367. get: function () {
  75368. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75369. },
  75370. /**
  75371. * Sets wether the color curves effect is enabled.
  75372. */
  75373. set: function (value) {
  75374. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75375. },
  75376. enumerable: true,
  75377. configurable: true
  75378. });
  75379. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  75380. /**
  75381. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  75382. */
  75383. get: function () {
  75384. return this.imageProcessingConfiguration.colorGradingTexture;
  75385. },
  75386. /**
  75387. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  75388. */
  75389. set: function (value) {
  75390. this.imageProcessingConfiguration.colorGradingTexture = value;
  75391. },
  75392. enumerable: true,
  75393. configurable: true
  75394. });
  75395. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  75396. /**
  75397. * Gets wether the color grading effect is enabled.
  75398. */
  75399. get: function () {
  75400. return this.imageProcessingConfiguration.colorGradingEnabled;
  75401. },
  75402. /**
  75403. * Gets wether the color grading effect is enabled.
  75404. */
  75405. set: function (value) {
  75406. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75407. },
  75408. enumerable: true,
  75409. configurable: true
  75410. });
  75411. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  75412. /**
  75413. * Gets exposure used in the effect.
  75414. */
  75415. get: function () {
  75416. return this.imageProcessingConfiguration.exposure;
  75417. },
  75418. /**
  75419. * Sets exposure used in the effect.
  75420. */
  75421. set: function (value) {
  75422. this.imageProcessingConfiguration.exposure = value;
  75423. },
  75424. enumerable: true,
  75425. configurable: true
  75426. });
  75427. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  75428. /**
  75429. * Gets wether tonemapping is enabled or not.
  75430. */
  75431. get: function () {
  75432. return this._imageProcessingConfiguration.toneMappingEnabled;
  75433. },
  75434. /**
  75435. * Sets wether tonemapping is enabled or not
  75436. */
  75437. set: function (value) {
  75438. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75439. },
  75440. enumerable: true,
  75441. configurable: true
  75442. });
  75443. ;
  75444. ;
  75445. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  75446. /**
  75447. * Gets contrast used in the effect.
  75448. */
  75449. get: function () {
  75450. return this.imageProcessingConfiguration.contrast;
  75451. },
  75452. /**
  75453. * Sets contrast used in the effect.
  75454. */
  75455. set: function (value) {
  75456. this.imageProcessingConfiguration.contrast = value;
  75457. },
  75458. enumerable: true,
  75459. configurable: true
  75460. });
  75461. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  75462. /**
  75463. * Gets Vignette stretch size.
  75464. */
  75465. get: function () {
  75466. return this.imageProcessingConfiguration.vignetteStretch;
  75467. },
  75468. /**
  75469. * Sets Vignette stretch size.
  75470. */
  75471. set: function (value) {
  75472. this.imageProcessingConfiguration.vignetteStretch = value;
  75473. },
  75474. enumerable: true,
  75475. configurable: true
  75476. });
  75477. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  75478. /**
  75479. * Gets Vignette centre X Offset.
  75480. */
  75481. get: function () {
  75482. return this.imageProcessingConfiguration.vignetteCentreX;
  75483. },
  75484. /**
  75485. * Sets Vignette centre X Offset.
  75486. */
  75487. set: function (value) {
  75488. this.imageProcessingConfiguration.vignetteCentreX = value;
  75489. },
  75490. enumerable: true,
  75491. configurable: true
  75492. });
  75493. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  75494. /**
  75495. * Gets Vignette centre Y Offset.
  75496. */
  75497. get: function () {
  75498. return this.imageProcessingConfiguration.vignetteCentreY;
  75499. },
  75500. /**
  75501. * Sets Vignette centre Y Offset.
  75502. */
  75503. set: function (value) {
  75504. this.imageProcessingConfiguration.vignetteCentreY = value;
  75505. },
  75506. enumerable: true,
  75507. configurable: true
  75508. });
  75509. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  75510. /**
  75511. * Gets Vignette weight or intensity of the vignette effect.
  75512. */
  75513. get: function () {
  75514. return this.imageProcessingConfiguration.vignetteWeight;
  75515. },
  75516. /**
  75517. * Sets Vignette weight or intensity of the vignette effect.
  75518. */
  75519. set: function (value) {
  75520. this.imageProcessingConfiguration.vignetteWeight = value;
  75521. },
  75522. enumerable: true,
  75523. configurable: true
  75524. });
  75525. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  75526. /**
  75527. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75528. * if vignetteEnabled is set to true.
  75529. */
  75530. get: function () {
  75531. return this.imageProcessingConfiguration.vignetteColor;
  75532. },
  75533. /**
  75534. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75535. * if vignetteEnabled is set to true.
  75536. */
  75537. set: function (value) {
  75538. this.imageProcessingConfiguration.vignetteColor = value;
  75539. },
  75540. enumerable: true,
  75541. configurable: true
  75542. });
  75543. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  75544. /**
  75545. * Gets Camera field of view used by the Vignette effect.
  75546. */
  75547. get: function () {
  75548. return this.imageProcessingConfiguration.vignetteCameraFov;
  75549. },
  75550. /**
  75551. * Sets Camera field of view used by the Vignette effect.
  75552. */
  75553. set: function (value) {
  75554. this.imageProcessingConfiguration.vignetteCameraFov = value;
  75555. },
  75556. enumerable: true,
  75557. configurable: true
  75558. });
  75559. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  75560. /**
  75561. * Gets the vignette blend mode allowing different kind of effect.
  75562. */
  75563. get: function () {
  75564. return this.imageProcessingConfiguration.vignetteBlendMode;
  75565. },
  75566. /**
  75567. * Sets the vignette blend mode allowing different kind of effect.
  75568. */
  75569. set: function (value) {
  75570. this.imageProcessingConfiguration.vignetteBlendMode = value;
  75571. },
  75572. enumerable: true,
  75573. configurable: true
  75574. });
  75575. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  75576. /**
  75577. * Gets wether the vignette effect is enabled.
  75578. */
  75579. get: function () {
  75580. return this.imageProcessingConfiguration.vignetteEnabled;
  75581. },
  75582. /**
  75583. * Sets wether the vignette effect is enabled.
  75584. */
  75585. set: function (value) {
  75586. this.imageProcessingConfiguration.vignetteEnabled = value;
  75587. },
  75588. enumerable: true,
  75589. configurable: true
  75590. });
  75591. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  75592. /**
  75593. * Gets wether the input of the processing is in Gamma or Linear Space.
  75594. */
  75595. get: function () {
  75596. return this._fromLinearSpace;
  75597. },
  75598. /**
  75599. * Sets wether the input of the processing is in Gamma or Linear Space.
  75600. */
  75601. set: function (value) {
  75602. if (this._fromLinearSpace === value) {
  75603. return;
  75604. }
  75605. this._fromLinearSpace = value;
  75606. this._updateParameters();
  75607. },
  75608. enumerable: true,
  75609. configurable: true
  75610. });
  75611. ImageProcessingPostProcess.prototype.getClassName = function () {
  75612. return "ImageProcessingPostProcess";
  75613. };
  75614. ImageProcessingPostProcess.prototype._updateParameters = function () {
  75615. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  75616. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  75617. var defines = "";
  75618. for (var define in this._defines) {
  75619. if (this._defines[define]) {
  75620. defines += "#define " + define + ";\r\n";
  75621. }
  75622. }
  75623. var samplers = ["textureSampler"];
  75624. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  75625. var uniforms = ["scale"];
  75626. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  75627. this.updateEffect(defines, uniforms, samplers);
  75628. };
  75629. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  75630. _super.prototype.dispose.call(this, camera);
  75631. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75632. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75633. }
  75634. this.imageProcessingConfiguration.applyByPostProcess = false;
  75635. };
  75636. __decorate([
  75637. BABYLON.serialize()
  75638. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  75639. return ImageProcessingPostProcess;
  75640. }(BABYLON.PostProcess));
  75641. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  75642. })(BABYLON || (BABYLON = {}));
  75643. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  75644. "use strict";
  75645. var BABYLON;
  75646. (function (BABYLON) {
  75647. var Bone = /** @class */ (function (_super) {
  75648. __extends(Bone, _super);
  75649. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  75650. if (parentBone === void 0) { parentBone = null; }
  75651. if (localMatrix === void 0) { localMatrix = null; }
  75652. if (restPose === void 0) { restPose = null; }
  75653. if (baseMatrix === void 0) { baseMatrix = null; }
  75654. if (index === void 0) { index = null; }
  75655. var _this = _super.call(this, name, skeleton.getScene()) || this;
  75656. _this.name = name;
  75657. _this.children = new Array();
  75658. _this.animations = new Array();
  75659. // Set this value to map this bone to a different index in the transform matrices.
  75660. // Set this value to -1 to exclude the bone from the transform matrices.
  75661. _this._index = null;
  75662. _this._worldTransform = new BABYLON.Matrix();
  75663. _this._absoluteTransform = new BABYLON.Matrix();
  75664. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  75665. _this._scaleMatrix = BABYLON.Matrix.Identity();
  75666. _this._scaleVector = BABYLON.Vector3.One();
  75667. _this._negateScaleChildren = BABYLON.Vector3.One();
  75668. _this._scalingDeterminant = 1;
  75669. _this._skeleton = skeleton;
  75670. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  75671. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  75672. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  75673. _this._index = index;
  75674. skeleton.bones.push(_this);
  75675. _this.setParent(parentBone, false);
  75676. _this._updateDifferenceMatrix();
  75677. return _this;
  75678. }
  75679. Object.defineProperty(Bone.prototype, "_matrix", {
  75680. get: function () {
  75681. return this._localMatrix;
  75682. },
  75683. set: function (val) {
  75684. if (this._localMatrix) {
  75685. this._localMatrix.copyFrom(val);
  75686. }
  75687. else {
  75688. this._localMatrix = val;
  75689. }
  75690. },
  75691. enumerable: true,
  75692. configurable: true
  75693. });
  75694. // Members
  75695. Bone.prototype.getSkeleton = function () {
  75696. return this._skeleton;
  75697. };
  75698. Bone.prototype.getParent = function () {
  75699. return this._parent;
  75700. };
  75701. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  75702. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  75703. if (this._parent === parent) {
  75704. return;
  75705. }
  75706. if (this._parent) {
  75707. var index = this._parent.children.indexOf(this);
  75708. if (index !== -1) {
  75709. this._parent.children.splice(index, 1);
  75710. }
  75711. }
  75712. this._parent = parent;
  75713. if (this._parent) {
  75714. this._parent.children.push(this);
  75715. }
  75716. if (updateDifferenceMatrix) {
  75717. this._updateDifferenceMatrix();
  75718. }
  75719. };
  75720. Bone.prototype.getLocalMatrix = function () {
  75721. return this._localMatrix;
  75722. };
  75723. Bone.prototype.getBaseMatrix = function () {
  75724. return this._baseMatrix;
  75725. };
  75726. Bone.prototype.getRestPose = function () {
  75727. return this._restPose;
  75728. };
  75729. Bone.prototype.returnToRest = function () {
  75730. this.updateMatrix(this._restPose.clone());
  75731. };
  75732. Bone.prototype.getWorldMatrix = function () {
  75733. return this._worldTransform;
  75734. };
  75735. Bone.prototype.getInvertedAbsoluteTransform = function () {
  75736. return this._invertedAbsoluteTransform;
  75737. };
  75738. Bone.prototype.getAbsoluteTransform = function () {
  75739. return this._absoluteTransform;
  75740. };
  75741. Object.defineProperty(Bone.prototype, "position", {
  75742. // Properties (matches AbstractMesh properties)
  75743. get: function () {
  75744. return this.getPosition();
  75745. },
  75746. set: function (newPosition) {
  75747. this.setPosition(newPosition);
  75748. },
  75749. enumerable: true,
  75750. configurable: true
  75751. });
  75752. Object.defineProperty(Bone.prototype, "rotation", {
  75753. get: function () {
  75754. return this.getRotation();
  75755. },
  75756. set: function (newRotation) {
  75757. this.setRotation(newRotation);
  75758. },
  75759. enumerable: true,
  75760. configurable: true
  75761. });
  75762. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  75763. get: function () {
  75764. return this.getRotationQuaternion();
  75765. },
  75766. set: function (newRotation) {
  75767. this.setRotationQuaternion(newRotation);
  75768. },
  75769. enumerable: true,
  75770. configurable: true
  75771. });
  75772. Object.defineProperty(Bone.prototype, "scaling", {
  75773. get: function () {
  75774. return this.getScale();
  75775. },
  75776. set: function (newScaling) {
  75777. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  75778. },
  75779. enumerable: true,
  75780. configurable: true
  75781. });
  75782. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  75783. /**
  75784. * Gets the animation properties override
  75785. */
  75786. get: function () {
  75787. return this._skeleton.animationPropertiesOverride;
  75788. },
  75789. enumerable: true,
  75790. configurable: true
  75791. });
  75792. // Methods
  75793. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  75794. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  75795. this._baseMatrix = matrix.clone();
  75796. this._localMatrix = matrix.clone();
  75797. this._skeleton._markAsDirty();
  75798. if (updateDifferenceMatrix) {
  75799. this._updateDifferenceMatrix();
  75800. }
  75801. };
  75802. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  75803. if (!rootMatrix) {
  75804. rootMatrix = this._baseMatrix;
  75805. }
  75806. if (this._parent) {
  75807. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  75808. }
  75809. else {
  75810. this._absoluteTransform.copyFrom(rootMatrix);
  75811. }
  75812. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  75813. for (var index = 0; index < this.children.length; index++) {
  75814. this.children[index]._updateDifferenceMatrix();
  75815. }
  75816. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  75817. };
  75818. Bone.prototype.markAsDirty = function () {
  75819. this._currentRenderId++;
  75820. this._childRenderId++;
  75821. this._skeleton._markAsDirty();
  75822. };
  75823. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  75824. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  75825. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  75826. // all animation may be coming from a library skeleton, so may need to create animation
  75827. if (this.animations.length === 0) {
  75828. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  75829. this.animations[0].setKeys([]);
  75830. }
  75831. // get animation info / verify there is such a range from the source bone
  75832. var sourceRange = source.animations[0].getRange(rangeName);
  75833. if (!sourceRange) {
  75834. return false;
  75835. }
  75836. var from = sourceRange.from;
  75837. var to = sourceRange.to;
  75838. var sourceKeys = source.animations[0].getKeys();
  75839. // rescaling prep
  75840. var sourceBoneLength = source.length;
  75841. var sourceParent = source.getParent();
  75842. var parent = this.getParent();
  75843. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  75844. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  75845. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  75846. var destKeys = this.animations[0].getKeys();
  75847. // loop vars declaration
  75848. var orig;
  75849. var origTranslation;
  75850. var mat;
  75851. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  75852. orig = sourceKeys[key];
  75853. if (orig.frame >= from && orig.frame <= to) {
  75854. if (rescaleAsRequired) {
  75855. mat = orig.value.clone();
  75856. // scale based on parent ratio, when bone has parent
  75857. if (parentScalingReqd) {
  75858. origTranslation = mat.getTranslation();
  75859. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  75860. // scale based on skeleton dimension ratio when root bone, and value is passed
  75861. }
  75862. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  75863. origTranslation = mat.getTranslation();
  75864. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  75865. // use original when root bone, and no data for skelDimensionsRatio
  75866. }
  75867. else {
  75868. mat = orig.value;
  75869. }
  75870. }
  75871. else {
  75872. mat = orig.value;
  75873. }
  75874. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  75875. }
  75876. }
  75877. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  75878. return true;
  75879. };
  75880. /**
  75881. * Translate the bone in local or world space.
  75882. * @param vec The amount to translate the bone.
  75883. * @param space The space that the translation is in.
  75884. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75885. */
  75886. Bone.prototype.translate = function (vec, space, mesh) {
  75887. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75888. var lm = this.getLocalMatrix();
  75889. if (space == BABYLON.Space.LOCAL) {
  75890. lm.m[12] += vec.x;
  75891. lm.m[13] += vec.y;
  75892. lm.m[14] += vec.z;
  75893. }
  75894. else {
  75895. var wm = null;
  75896. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75897. if (mesh) {
  75898. wm = mesh.getWorldMatrix();
  75899. }
  75900. this._skeleton.computeAbsoluteTransforms();
  75901. var tmat = Bone._tmpMats[0];
  75902. var tvec = Bone._tmpVecs[0];
  75903. if (this._parent) {
  75904. if (mesh && wm) {
  75905. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75906. tmat.multiplyToRef(wm, tmat);
  75907. }
  75908. else {
  75909. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75910. }
  75911. }
  75912. tmat.m[12] = 0;
  75913. tmat.m[13] = 0;
  75914. tmat.m[14] = 0;
  75915. tmat.invert();
  75916. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  75917. lm.m[12] += tvec.x;
  75918. lm.m[13] += tvec.y;
  75919. lm.m[14] += tvec.z;
  75920. }
  75921. this.markAsDirty();
  75922. };
  75923. /**
  75924. * Set the postion of the bone in local or world space.
  75925. * @param position The position to set the bone.
  75926. * @param space The space that the position is in.
  75927. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75928. */
  75929. Bone.prototype.setPosition = function (position, space, mesh) {
  75930. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75931. var lm = this.getLocalMatrix();
  75932. if (space == BABYLON.Space.LOCAL) {
  75933. lm.m[12] = position.x;
  75934. lm.m[13] = position.y;
  75935. lm.m[14] = position.z;
  75936. }
  75937. else {
  75938. var wm = null;
  75939. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75940. if (mesh) {
  75941. wm = mesh.getWorldMatrix();
  75942. }
  75943. this._skeleton.computeAbsoluteTransforms();
  75944. var tmat = Bone._tmpMats[0];
  75945. var vec = Bone._tmpVecs[0];
  75946. if (this._parent) {
  75947. if (mesh && wm) {
  75948. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75949. tmat.multiplyToRef(wm, tmat);
  75950. }
  75951. else {
  75952. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75953. }
  75954. }
  75955. tmat.invert();
  75956. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  75957. lm.m[12] = vec.x;
  75958. lm.m[13] = vec.y;
  75959. lm.m[14] = vec.z;
  75960. }
  75961. this.markAsDirty();
  75962. };
  75963. /**
  75964. * Set the absolute postion of the bone (world space).
  75965. * @param position The position to set the bone.
  75966. * @param mesh The mesh that this bone is attached to.
  75967. */
  75968. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  75969. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  75970. };
  75971. /**
  75972. * Set the scale of the bone on the x, y and z axes.
  75973. * @param x The scale of the bone on the x axis.
  75974. * @param x The scale of the bone on the y axis.
  75975. * @param z The scale of the bone on the z axis.
  75976. * @param scaleChildren Set this to true if children of the bone should be scaled.
  75977. */
  75978. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  75979. if (scaleChildren === void 0) { scaleChildren = false; }
  75980. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  75981. if (!scaleChildren) {
  75982. this._negateScaleChildren.x = 1 / x;
  75983. this._negateScaleChildren.y = 1 / y;
  75984. this._negateScaleChildren.z = 1 / z;
  75985. }
  75986. this._syncScaleVector();
  75987. }
  75988. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  75989. };
  75990. /**
  75991. * Scale the bone on the x, y and z axes.
  75992. * @param x The amount to scale the bone on the x axis.
  75993. * @param x The amount to scale the bone on the y axis.
  75994. * @param z The amount to scale the bone on the z axis.
  75995. * @param scaleChildren Set this to true if children of the bone should be scaled.
  75996. */
  75997. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  75998. if (scaleChildren === void 0) { scaleChildren = false; }
  75999. var locMat = this.getLocalMatrix();
  76000. var origLocMat = Bone._tmpMats[0];
  76001. origLocMat.copyFrom(locMat);
  76002. var origLocMatInv = Bone._tmpMats[1];
  76003. origLocMatInv.copyFrom(origLocMat);
  76004. origLocMatInv.invert();
  76005. var scaleMat = Bone._tmpMats[2];
  76006. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  76007. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  76008. this._scaleVector.x *= x;
  76009. this._scaleVector.y *= y;
  76010. this._scaleVector.z *= z;
  76011. locMat.multiplyToRef(origLocMatInv, locMat);
  76012. locMat.multiplyToRef(scaleMat, locMat);
  76013. locMat.multiplyToRef(origLocMat, locMat);
  76014. var parent = this.getParent();
  76015. if (parent) {
  76016. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  76017. }
  76018. else {
  76019. this.getAbsoluteTransform().copyFrom(locMat);
  76020. }
  76021. var len = this.children.length;
  76022. scaleMat.invert();
  76023. for (var i = 0; i < len; i++) {
  76024. var child = this.children[i];
  76025. var cm = child.getLocalMatrix();
  76026. cm.multiplyToRef(scaleMat, cm);
  76027. var lm = child.getLocalMatrix();
  76028. lm.m[12] *= x;
  76029. lm.m[13] *= y;
  76030. lm.m[14] *= z;
  76031. }
  76032. this.computeAbsoluteTransforms();
  76033. if (scaleChildren) {
  76034. for (var i = 0; i < len; i++) {
  76035. this.children[i].scale(x, y, z, scaleChildren);
  76036. }
  76037. }
  76038. this.markAsDirty();
  76039. };
  76040. /**
  76041. * Set the yaw, pitch, and roll of the bone in local or world space.
  76042. * @param yaw The rotation of the bone on the y axis.
  76043. * @param pitch The rotation of the bone on the x axis.
  76044. * @param roll The rotation of the bone on the z axis.
  76045. * @param space The space that the axes of rotation are in.
  76046. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76047. */
  76048. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  76049. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76050. var rotMat = Bone._tmpMats[0];
  76051. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  76052. var rotMatInv = Bone._tmpMats[1];
  76053. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76054. rotMatInv.multiplyToRef(rotMat, rotMat);
  76055. this._rotateWithMatrix(rotMat, space, mesh);
  76056. };
  76057. /**
  76058. * Rotate the bone on an axis in local or world space.
  76059. * @param axis The axis to rotate the bone on.
  76060. * @param amount The amount to rotate the bone.
  76061. * @param space The space that the axis is in.
  76062. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76063. */
  76064. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  76065. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76066. var rmat = Bone._tmpMats[0];
  76067. rmat.m[12] = 0;
  76068. rmat.m[13] = 0;
  76069. rmat.m[14] = 0;
  76070. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  76071. this._rotateWithMatrix(rmat, space, mesh);
  76072. };
  76073. /**
  76074. * Set the rotation of the bone to a particular axis angle in local or world space.
  76075. * @param axis The axis to rotate the bone on.
  76076. * @param angle The angle that the bone should be rotated to.
  76077. * @param space The space that the axis is in.
  76078. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76079. */
  76080. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  76081. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76082. var rotMat = Bone._tmpMats[0];
  76083. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  76084. var rotMatInv = Bone._tmpMats[1];
  76085. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76086. rotMatInv.multiplyToRef(rotMat, rotMat);
  76087. this._rotateWithMatrix(rotMat, space, mesh);
  76088. };
  76089. /**
  76090. * Set the euler rotation of the bone in local of world space.
  76091. * @param rotation The euler rotation that the bone should be set to.
  76092. * @param space The space that the rotation is in.
  76093. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76094. */
  76095. Bone.prototype.setRotation = function (rotation, space, mesh) {
  76096. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76097. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  76098. };
  76099. /**
  76100. * Set the quaternion rotation of the bone in local of world space.
  76101. * @param quat The quaternion rotation that the bone should be set to.
  76102. * @param space The space that the rotation is in.
  76103. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76104. */
  76105. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  76106. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76107. var rotMatInv = Bone._tmpMats[0];
  76108. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76109. var rotMat = Bone._tmpMats[1];
  76110. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  76111. rotMatInv.multiplyToRef(rotMat, rotMat);
  76112. this._rotateWithMatrix(rotMat, space, mesh);
  76113. };
  76114. /**
  76115. * Set the rotation matrix of the bone in local of world space.
  76116. * @param rotMat The rotation matrix that the bone should be set to.
  76117. * @param space The space that the rotation is in.
  76118. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76119. */
  76120. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  76121. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76122. var rotMatInv = Bone._tmpMats[0];
  76123. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76124. var rotMat2 = Bone._tmpMats[1];
  76125. rotMat2.copyFrom(rotMat);
  76126. rotMatInv.multiplyToRef(rotMat, rotMat2);
  76127. this._rotateWithMatrix(rotMat2, space, mesh);
  76128. };
  76129. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  76130. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76131. var lmat = this.getLocalMatrix();
  76132. var lx = lmat.m[12];
  76133. var ly = lmat.m[13];
  76134. var lz = lmat.m[14];
  76135. var parent = this.getParent();
  76136. var parentScale = Bone._tmpMats[3];
  76137. var parentScaleInv = Bone._tmpMats[4];
  76138. if (parent) {
  76139. if (space == BABYLON.Space.WORLD) {
  76140. if (mesh) {
  76141. parentScale.copyFrom(mesh.getWorldMatrix());
  76142. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  76143. }
  76144. else {
  76145. parentScale.copyFrom(parent.getAbsoluteTransform());
  76146. }
  76147. }
  76148. else {
  76149. parentScale = parent._scaleMatrix;
  76150. }
  76151. parentScaleInv.copyFrom(parentScale);
  76152. parentScaleInv.invert();
  76153. lmat.multiplyToRef(parentScale, lmat);
  76154. lmat.multiplyToRef(rmat, lmat);
  76155. lmat.multiplyToRef(parentScaleInv, lmat);
  76156. }
  76157. else {
  76158. if (space == BABYLON.Space.WORLD && mesh) {
  76159. parentScale.copyFrom(mesh.getWorldMatrix());
  76160. parentScaleInv.copyFrom(parentScale);
  76161. parentScaleInv.invert();
  76162. lmat.multiplyToRef(parentScale, lmat);
  76163. lmat.multiplyToRef(rmat, lmat);
  76164. lmat.multiplyToRef(parentScaleInv, lmat);
  76165. }
  76166. else {
  76167. lmat.multiplyToRef(rmat, lmat);
  76168. }
  76169. }
  76170. lmat.m[12] = lx;
  76171. lmat.m[13] = ly;
  76172. lmat.m[14] = lz;
  76173. this.computeAbsoluteTransforms();
  76174. this.markAsDirty();
  76175. };
  76176. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  76177. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76178. if (space == BABYLON.Space.WORLD) {
  76179. var scaleMatrix = Bone._tmpMats[2];
  76180. scaleMatrix.copyFrom(this._scaleMatrix);
  76181. rotMatInv.copyFrom(this.getAbsoluteTransform());
  76182. if (mesh) {
  76183. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  76184. var meshScale = Bone._tmpMats[3];
  76185. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  76186. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  76187. }
  76188. rotMatInv.invert();
  76189. scaleMatrix.m[0] *= this._scalingDeterminant;
  76190. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  76191. }
  76192. else {
  76193. rotMatInv.copyFrom(this.getLocalMatrix());
  76194. rotMatInv.invert();
  76195. var scaleMatrix = Bone._tmpMats[2];
  76196. scaleMatrix.copyFrom(this._scaleMatrix);
  76197. if (this._parent) {
  76198. var pscaleMatrix = Bone._tmpMats[3];
  76199. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  76200. pscaleMatrix.invert();
  76201. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  76202. }
  76203. else {
  76204. scaleMatrix.m[0] *= this._scalingDeterminant;
  76205. }
  76206. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  76207. }
  76208. };
  76209. /**
  76210. * Get the scale of the bone
  76211. * @returns the scale of the bone
  76212. */
  76213. Bone.prototype.getScale = function () {
  76214. return this._scaleVector.clone();
  76215. };
  76216. /**
  76217. * Copy the scale of the bone to a vector3.
  76218. * @param result The vector3 to copy the scale to
  76219. */
  76220. Bone.prototype.getScaleToRef = function (result) {
  76221. result.copyFrom(this._scaleVector);
  76222. };
  76223. /**
  76224. * Get the position of the bone in local or world space.
  76225. * @param space The space that the returned position is in.
  76226. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76227. * @returns The position of the bone
  76228. */
  76229. Bone.prototype.getPosition = function (space, mesh) {
  76230. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76231. if (mesh === void 0) { mesh = null; }
  76232. var pos = BABYLON.Vector3.Zero();
  76233. this.getPositionToRef(space, mesh, pos);
  76234. return pos;
  76235. };
  76236. /**
  76237. * Copy the position of the bone to a vector3 in local or world space.
  76238. * @param space The space that the returned position is in.
  76239. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76240. * @param result The vector3 to copy the position to.
  76241. */
  76242. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  76243. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76244. if (space == BABYLON.Space.LOCAL) {
  76245. var lm = this.getLocalMatrix();
  76246. result.x = lm.m[12];
  76247. result.y = lm.m[13];
  76248. result.z = lm.m[14];
  76249. }
  76250. else {
  76251. var wm = null;
  76252. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76253. if (mesh) {
  76254. wm = mesh.getWorldMatrix();
  76255. }
  76256. this._skeleton.computeAbsoluteTransforms();
  76257. var tmat = Bone._tmpMats[0];
  76258. if (mesh && wm) {
  76259. tmat.copyFrom(this.getAbsoluteTransform());
  76260. tmat.multiplyToRef(wm, tmat);
  76261. }
  76262. else {
  76263. tmat = this.getAbsoluteTransform();
  76264. }
  76265. result.x = tmat.m[12];
  76266. result.y = tmat.m[13];
  76267. result.z = tmat.m[14];
  76268. }
  76269. };
  76270. /**
  76271. * Get the absolute position of the bone (world space).
  76272. * @param mesh The mesh that this bone is attached to.
  76273. * @returns The absolute position of the bone
  76274. */
  76275. Bone.prototype.getAbsolutePosition = function (mesh) {
  76276. if (mesh === void 0) { mesh = null; }
  76277. var pos = BABYLON.Vector3.Zero();
  76278. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  76279. return pos;
  76280. };
  76281. /**
  76282. * Copy the absolute position of the bone (world space) to the result param.
  76283. * @param mesh The mesh that this bone is attached to.
  76284. * @param result The vector3 to copy the absolute position to.
  76285. */
  76286. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  76287. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  76288. };
  76289. /**
  76290. * Compute the absolute transforms of this bone and its children.
  76291. */
  76292. Bone.prototype.computeAbsoluteTransforms = function () {
  76293. if (this._parent) {
  76294. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76295. }
  76296. else {
  76297. this._absoluteTransform.copyFrom(this._localMatrix);
  76298. var poseMatrix = this._skeleton.getPoseMatrix();
  76299. if (poseMatrix) {
  76300. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  76301. }
  76302. }
  76303. var children = this.children;
  76304. var len = children.length;
  76305. for (var i = 0; i < len; i++) {
  76306. children[i].computeAbsoluteTransforms();
  76307. }
  76308. };
  76309. Bone.prototype._syncScaleVector = function () {
  76310. var lm = this.getLocalMatrix();
  76311. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  76312. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  76313. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  76314. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  76315. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  76316. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  76317. this._scaleVector.x = xs * Math.sqrt(xsq);
  76318. this._scaleVector.y = ys * Math.sqrt(ysq);
  76319. this._scaleVector.z = zs * Math.sqrt(zsq);
  76320. if (this._parent) {
  76321. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  76322. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  76323. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  76324. }
  76325. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  76326. };
  76327. /**
  76328. * Get the world direction from an axis that is in the local space of the bone.
  76329. * @param localAxis The local direction that is used to compute the world direction.
  76330. * @param mesh The mesh that this bone is attached to.
  76331. * @returns The world direction
  76332. */
  76333. Bone.prototype.getDirection = function (localAxis, mesh) {
  76334. if (mesh === void 0) { mesh = null; }
  76335. var result = BABYLON.Vector3.Zero();
  76336. this.getDirectionToRef(localAxis, mesh, result);
  76337. return result;
  76338. };
  76339. /**
  76340. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  76341. * @param localAxis The local direction that is used to compute the world direction.
  76342. * @param mesh The mesh that this bone is attached to.
  76343. * @param result The vector3 that the world direction will be copied to.
  76344. */
  76345. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  76346. if (mesh === void 0) { mesh = null; }
  76347. var wm = null;
  76348. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76349. if (mesh) {
  76350. wm = mesh.getWorldMatrix();
  76351. }
  76352. this._skeleton.computeAbsoluteTransforms();
  76353. var mat = Bone._tmpMats[0];
  76354. mat.copyFrom(this.getAbsoluteTransform());
  76355. if (mesh && wm) {
  76356. mat.multiplyToRef(wm, mat);
  76357. }
  76358. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  76359. result.normalize();
  76360. };
  76361. /**
  76362. * Get the euler rotation of the bone in local or world space.
  76363. * @param space The space that the rotation should be in.
  76364. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76365. * @returns The euler rotation
  76366. */
  76367. Bone.prototype.getRotation = function (space, mesh) {
  76368. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76369. if (mesh === void 0) { mesh = null; }
  76370. var result = BABYLON.Vector3.Zero();
  76371. this.getRotationToRef(space, mesh, result);
  76372. return result;
  76373. };
  76374. /**
  76375. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  76376. * @param space The space that the rotation should be in.
  76377. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76378. * @param result The vector3 that the rotation should be copied to.
  76379. */
  76380. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  76381. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76382. if (mesh === void 0) { mesh = null; }
  76383. var quat = Bone._tmpQuat;
  76384. this.getRotationQuaternionToRef(space, mesh, quat);
  76385. quat.toEulerAnglesToRef(result);
  76386. };
  76387. /**
  76388. * Get the quaternion rotation of the bone in either local or world space.
  76389. * @param space The space that the rotation should be in.
  76390. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76391. * @returns The quaternion rotation
  76392. */
  76393. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  76394. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76395. if (mesh === void 0) { mesh = null; }
  76396. var result = BABYLON.Quaternion.Identity();
  76397. this.getRotationQuaternionToRef(space, mesh, result);
  76398. return result;
  76399. };
  76400. /**
  76401. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  76402. * @param space The space that the rotation should be in.
  76403. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76404. * @param result The quaternion that the rotation should be copied to.
  76405. */
  76406. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  76407. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76408. if (mesh === void 0) { mesh = null; }
  76409. if (space == BABYLON.Space.LOCAL) {
  76410. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  76411. }
  76412. else {
  76413. var mat = Bone._tmpMats[0];
  76414. var amat = this.getAbsoluteTransform();
  76415. if (mesh) {
  76416. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  76417. }
  76418. else {
  76419. mat.copyFrom(amat);
  76420. }
  76421. mat.m[0] *= this._scalingDeterminant;
  76422. mat.m[1] *= this._scalingDeterminant;
  76423. mat.m[2] *= this._scalingDeterminant;
  76424. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  76425. }
  76426. };
  76427. /**
  76428. * Get the rotation matrix of the bone in local or world space.
  76429. * @param space The space that the rotation should be in.
  76430. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76431. * @returns The rotation matrix
  76432. */
  76433. Bone.prototype.getRotationMatrix = function (space, mesh) {
  76434. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76435. var result = BABYLON.Matrix.Identity();
  76436. this.getRotationMatrixToRef(space, mesh, result);
  76437. return result;
  76438. };
  76439. /**
  76440. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  76441. * @param space The space that the rotation should be in.
  76442. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76443. * @param result The quaternion that the rotation should be copied to.
  76444. */
  76445. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  76446. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76447. if (space == BABYLON.Space.LOCAL) {
  76448. this.getLocalMatrix().getRotationMatrixToRef(result);
  76449. }
  76450. else {
  76451. var mat = Bone._tmpMats[0];
  76452. var amat = this.getAbsoluteTransform();
  76453. if (mesh) {
  76454. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  76455. }
  76456. else {
  76457. mat.copyFrom(amat);
  76458. }
  76459. mat.m[0] *= this._scalingDeterminant;
  76460. mat.m[1] *= this._scalingDeterminant;
  76461. mat.m[2] *= this._scalingDeterminant;
  76462. mat.getRotationMatrixToRef(result);
  76463. }
  76464. };
  76465. /**
  76466. * Get the world position of a point that is in the local space of the bone.
  76467. * @param position The local position
  76468. * @param mesh The mesh that this bone is attached to.
  76469. * @returns The world position
  76470. */
  76471. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  76472. if (mesh === void 0) { mesh = null; }
  76473. var result = BABYLON.Vector3.Zero();
  76474. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  76475. return result;
  76476. };
  76477. /**
  76478. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  76479. * @param position The local position
  76480. * @param mesh The mesh that this bone is attached to.
  76481. * @param result The vector3 that the world position should be copied to.
  76482. */
  76483. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  76484. if (mesh === void 0) { mesh = null; }
  76485. var wm = null;
  76486. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76487. if (mesh) {
  76488. wm = mesh.getWorldMatrix();
  76489. }
  76490. this._skeleton.computeAbsoluteTransforms();
  76491. var tmat = Bone._tmpMats[0];
  76492. if (mesh && wm) {
  76493. tmat.copyFrom(this.getAbsoluteTransform());
  76494. tmat.multiplyToRef(wm, tmat);
  76495. }
  76496. else {
  76497. tmat = this.getAbsoluteTransform();
  76498. }
  76499. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76500. };
  76501. /**
  76502. * Get the local position of a point that is in world space.
  76503. * @param position The world position
  76504. * @param mesh The mesh that this bone is attached to.
  76505. * @returns The local position
  76506. */
  76507. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  76508. if (mesh === void 0) { mesh = null; }
  76509. var result = BABYLON.Vector3.Zero();
  76510. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  76511. return result;
  76512. };
  76513. /**
  76514. * Get the local position of a point that is in world space and copy it to the result param.
  76515. * @param position The world position
  76516. * @param mesh The mesh that this bone is attached to.
  76517. * @param result The vector3 that the local position should be copied to.
  76518. */
  76519. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  76520. if (mesh === void 0) { mesh = null; }
  76521. var wm = null;
  76522. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76523. if (mesh) {
  76524. wm = mesh.getWorldMatrix();
  76525. }
  76526. this._skeleton.computeAbsoluteTransforms();
  76527. var tmat = Bone._tmpMats[0];
  76528. tmat.copyFrom(this.getAbsoluteTransform());
  76529. if (mesh && wm) {
  76530. tmat.multiplyToRef(wm, tmat);
  76531. }
  76532. tmat.invert();
  76533. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76534. };
  76535. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76536. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  76537. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76538. return Bone;
  76539. }(BABYLON.Node));
  76540. BABYLON.Bone = Bone;
  76541. })(BABYLON || (BABYLON = {}));
  76542. //# sourceMappingURL=babylon.bone.js.map
  76543. "use strict";
  76544. var BABYLON;
  76545. (function (BABYLON) {
  76546. var BoneIKController = /** @class */ (function () {
  76547. function BoneIKController(mesh, bone, options) {
  76548. this.targetPosition = BABYLON.Vector3.Zero();
  76549. this.poleTargetPosition = BABYLON.Vector3.Zero();
  76550. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  76551. this.poleAngle = 0;
  76552. this.slerpAmount = 1;
  76553. this._bone1Quat = BABYLON.Quaternion.Identity();
  76554. this._bone1Mat = BABYLON.Matrix.Identity();
  76555. this._bone2Ang = Math.PI;
  76556. this._maxAngle = Math.PI;
  76557. this._rightHandedSystem = false;
  76558. this._bendAxis = BABYLON.Vector3.Right();
  76559. this._slerping = false;
  76560. this._adjustRoll = 0;
  76561. this._bone2 = bone;
  76562. this._bone1 = bone.getParent();
  76563. if (!this._bone1) {
  76564. return;
  76565. }
  76566. this.mesh = mesh;
  76567. var bonePos = bone.getPosition();
  76568. if (bone.getAbsoluteTransform().determinant() > 0) {
  76569. this._rightHandedSystem = true;
  76570. this._bendAxis.x = 0;
  76571. this._bendAxis.y = 0;
  76572. this._bendAxis.z = -1;
  76573. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  76574. this._adjustRoll = Math.PI * .5;
  76575. this._bendAxis.z = 1;
  76576. }
  76577. }
  76578. if (this._bone1.length) {
  76579. var boneScale1 = this._bone1.getScale();
  76580. var boneScale2 = this._bone2.getScale();
  76581. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  76582. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  76583. }
  76584. else if (this._bone1.children[0]) {
  76585. mesh.computeWorldMatrix(true);
  76586. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  76587. var pos2 = this._bone2.getAbsolutePosition(mesh);
  76588. var pos3 = this._bone1.getAbsolutePosition(mesh);
  76589. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  76590. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  76591. }
  76592. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  76593. this.maxAngle = Math.PI;
  76594. if (options) {
  76595. if (options.targetMesh) {
  76596. this.targetMesh = options.targetMesh;
  76597. this.targetMesh.computeWorldMatrix(true);
  76598. }
  76599. if (options.poleTargetMesh) {
  76600. this.poleTargetMesh = options.poleTargetMesh;
  76601. this.poleTargetMesh.computeWorldMatrix(true);
  76602. }
  76603. else if (options.poleTargetBone) {
  76604. this.poleTargetBone = options.poleTargetBone;
  76605. }
  76606. else if (this._bone1.getParent()) {
  76607. this.poleTargetBone = this._bone1.getParent();
  76608. }
  76609. if (options.poleTargetLocalOffset) {
  76610. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  76611. }
  76612. if (options.poleAngle) {
  76613. this.poleAngle = options.poleAngle;
  76614. }
  76615. if (options.bendAxis) {
  76616. this._bendAxis.copyFrom(options.bendAxis);
  76617. }
  76618. if (options.maxAngle) {
  76619. this.maxAngle = options.maxAngle;
  76620. }
  76621. if (options.slerpAmount) {
  76622. this.slerpAmount = options.slerpAmount;
  76623. }
  76624. }
  76625. }
  76626. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  76627. get: function () {
  76628. return this._maxAngle;
  76629. },
  76630. set: function (value) {
  76631. this._setMaxAngle(value);
  76632. },
  76633. enumerable: true,
  76634. configurable: true
  76635. });
  76636. BoneIKController.prototype._setMaxAngle = function (ang) {
  76637. if (ang < 0) {
  76638. ang = 0;
  76639. }
  76640. if (ang > Math.PI || ang == undefined) {
  76641. ang = Math.PI;
  76642. }
  76643. this._maxAngle = ang;
  76644. var a = this._bone1Length;
  76645. var b = this._bone2Length;
  76646. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  76647. };
  76648. BoneIKController.prototype.update = function () {
  76649. var bone1 = this._bone1;
  76650. if (!bone1) {
  76651. return;
  76652. }
  76653. var target = this.targetPosition;
  76654. var poleTarget = this.poleTargetPosition;
  76655. var mat1 = BoneIKController._tmpMats[0];
  76656. var mat2 = BoneIKController._tmpMats[1];
  76657. if (this.targetMesh) {
  76658. target.copyFrom(this.targetMesh.getAbsolutePosition());
  76659. }
  76660. if (this.poleTargetBone) {
  76661. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  76662. }
  76663. else if (this.poleTargetMesh) {
  76664. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  76665. }
  76666. var bonePos = BoneIKController._tmpVecs[0];
  76667. var zaxis = BoneIKController._tmpVecs[1];
  76668. var xaxis = BoneIKController._tmpVecs[2];
  76669. var yaxis = BoneIKController._tmpVecs[3];
  76670. var upAxis = BoneIKController._tmpVecs[4];
  76671. var _tmpQuat = BoneIKController._tmpQuat;
  76672. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  76673. poleTarget.subtractToRef(bonePos, upAxis);
  76674. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  76675. upAxis.y = 1;
  76676. }
  76677. else {
  76678. upAxis.normalize();
  76679. }
  76680. target.subtractToRef(bonePos, yaxis);
  76681. yaxis.normalize();
  76682. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  76683. zaxis.normalize();
  76684. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  76685. xaxis.normalize();
  76686. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  76687. var a = this._bone1Length;
  76688. var b = this._bone2Length;
  76689. var c = BABYLON.Vector3.Distance(bonePos, target);
  76690. if (this._maxReach > 0) {
  76691. c = Math.min(this._maxReach, c);
  76692. }
  76693. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  76694. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  76695. if (acosa > 1) {
  76696. acosa = 1;
  76697. }
  76698. if (acosb > 1) {
  76699. acosb = 1;
  76700. }
  76701. if (acosa < -1) {
  76702. acosa = -1;
  76703. }
  76704. if (acosb < -1) {
  76705. acosb = -1;
  76706. }
  76707. var angA = Math.acos(acosa);
  76708. var angB = Math.acos(acosb);
  76709. var angC = -angA - angB;
  76710. if (this._rightHandedSystem) {
  76711. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  76712. mat2.multiplyToRef(mat1, mat1);
  76713. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  76714. mat2.multiplyToRef(mat1, mat1);
  76715. }
  76716. else {
  76717. var _tmpVec = BoneIKController._tmpVecs[5];
  76718. _tmpVec.copyFrom(this._bendAxis);
  76719. _tmpVec.x *= -1;
  76720. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  76721. mat2.multiplyToRef(mat1, mat1);
  76722. }
  76723. if (this.poleAngle) {
  76724. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  76725. mat1.multiplyToRef(mat2, mat1);
  76726. }
  76727. if (this._bone1) {
  76728. if (this.slerpAmount < 1) {
  76729. if (!this._slerping) {
  76730. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  76731. }
  76732. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  76733. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  76734. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  76735. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  76736. this._slerping = true;
  76737. }
  76738. else {
  76739. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  76740. this._bone1Mat.copyFrom(mat1);
  76741. this._slerping = false;
  76742. }
  76743. }
  76744. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  76745. this._bone2Ang = angC;
  76746. };
  76747. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76748. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  76749. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76750. return BoneIKController;
  76751. }());
  76752. BABYLON.BoneIKController = BoneIKController;
  76753. })(BABYLON || (BABYLON = {}));
  76754. //# sourceMappingURL=babylon.boneIKController.js.map
  76755. "use strict";
  76756. var BABYLON;
  76757. (function (BABYLON) {
  76758. var BoneLookController = /** @class */ (function () {
  76759. /**
  76760. * Create a BoneLookController
  76761. * @param mesh the mesh that the bone belongs to
  76762. * @param bone the bone that will be looking to the target
  76763. * @param target the target Vector3 to look at
  76764. * @param settings optional settings:
  76765. * - maxYaw: the maximum angle the bone will yaw to
  76766. * - minYaw: the minimum angle the bone will yaw to
  76767. * - maxPitch: the maximum angle the bone will pitch to
  76768. * - minPitch: the minimum angle the bone will yaw to
  76769. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  76770. * - upAxis: the up axis of the coordinate system
  76771. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  76772. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  76773. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  76774. * - adjustYaw: used to make an adjustment to the yaw of the bone
  76775. * - adjustPitch: used to make an adjustment to the pitch of the bone
  76776. * - adjustRoll: used to make an adjustment to the roll of the bone
  76777. **/
  76778. function BoneLookController(mesh, bone, target, options) {
  76779. /**
  76780. * The up axis of the coordinate system that is used when the bone is rotated.
  76781. */
  76782. this.upAxis = BABYLON.Vector3.Up();
  76783. /**
  76784. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  76785. */
  76786. this.upAxisSpace = BABYLON.Space.LOCAL;
  76787. /**
  76788. * Used to make an adjustment to the yaw of the bone.
  76789. */
  76790. this.adjustYaw = 0;
  76791. /**
  76792. * Used to make an adjustment to the pitch of the bone.
  76793. */
  76794. this.adjustPitch = 0;
  76795. /**
  76796. * Used to make an adjustment to the roll of the bone.
  76797. */
  76798. this.adjustRoll = 0;
  76799. /**
  76800. * 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).
  76801. */
  76802. this.slerpAmount = 1;
  76803. this._boneQuat = BABYLON.Quaternion.Identity();
  76804. this._slerping = false;
  76805. this._firstFrameSkipped = false;
  76806. this._fowardAxis = BABYLON.Vector3.Forward();
  76807. this.mesh = mesh;
  76808. this.bone = bone;
  76809. this.target = target;
  76810. if (options) {
  76811. if (options.adjustYaw) {
  76812. this.adjustYaw = options.adjustYaw;
  76813. }
  76814. if (options.adjustPitch) {
  76815. this.adjustPitch = options.adjustPitch;
  76816. }
  76817. if (options.adjustRoll) {
  76818. this.adjustRoll = options.adjustRoll;
  76819. }
  76820. if (options.maxYaw != null) {
  76821. this.maxYaw = options.maxYaw;
  76822. }
  76823. else {
  76824. this.maxYaw = Math.PI;
  76825. }
  76826. if (options.minYaw != null) {
  76827. this.minYaw = options.minYaw;
  76828. }
  76829. else {
  76830. this.minYaw = -Math.PI;
  76831. }
  76832. if (options.maxPitch != null) {
  76833. this.maxPitch = options.maxPitch;
  76834. }
  76835. else {
  76836. this.maxPitch = Math.PI;
  76837. }
  76838. if (options.minPitch != null) {
  76839. this.minPitch = options.minPitch;
  76840. }
  76841. else {
  76842. this.minPitch = -Math.PI;
  76843. }
  76844. if (options.slerpAmount != null) {
  76845. this.slerpAmount = options.slerpAmount;
  76846. }
  76847. if (options.upAxis != null) {
  76848. this.upAxis = options.upAxis;
  76849. }
  76850. if (options.upAxisSpace != null) {
  76851. this.upAxisSpace = options.upAxisSpace;
  76852. }
  76853. if (options.yawAxis != null || options.pitchAxis != null) {
  76854. var newYawAxis = BABYLON.Axis.Y;
  76855. var newPitchAxis = BABYLON.Axis.X;
  76856. if (options.yawAxis != null) {
  76857. newYawAxis = options.yawAxis.clone();
  76858. newYawAxis.normalize();
  76859. }
  76860. if (options.pitchAxis != null) {
  76861. newPitchAxis = options.pitchAxis.clone();
  76862. newPitchAxis.normalize();
  76863. }
  76864. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  76865. this._transformYawPitch = BABYLON.Matrix.Identity();
  76866. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  76867. this._transformYawPitchInv = this._transformYawPitch.clone();
  76868. this._transformYawPitch.invert();
  76869. }
  76870. }
  76871. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  76872. this.upAxisSpace = BABYLON.Space.LOCAL;
  76873. }
  76874. }
  76875. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  76876. /**
  76877. * Get/set the minimum yaw angle that the bone can look to.
  76878. */
  76879. get: function () {
  76880. return this._minYaw;
  76881. },
  76882. set: function (value) {
  76883. this._minYaw = value;
  76884. this._minYawSin = Math.sin(value);
  76885. this._minYawCos = Math.cos(value);
  76886. if (this._maxYaw != null) {
  76887. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  76888. this._yawRange = this._maxYaw - this._minYaw;
  76889. }
  76890. },
  76891. enumerable: true,
  76892. configurable: true
  76893. });
  76894. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  76895. /**
  76896. * Get/set the maximum yaw angle that the bone can look to.
  76897. */
  76898. get: function () {
  76899. return this._maxYaw;
  76900. },
  76901. set: function (value) {
  76902. this._maxYaw = value;
  76903. this._maxYawSin = Math.sin(value);
  76904. this._maxYawCos = Math.cos(value);
  76905. if (this._minYaw != null) {
  76906. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  76907. this._yawRange = this._maxYaw - this._minYaw;
  76908. }
  76909. },
  76910. enumerable: true,
  76911. configurable: true
  76912. });
  76913. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  76914. /**
  76915. * Get/set the minimum pitch angle that the bone can look to.
  76916. */
  76917. get: function () {
  76918. return this._minPitch;
  76919. },
  76920. set: function (value) {
  76921. this._minPitch = value;
  76922. this._minPitchTan = Math.tan(value);
  76923. },
  76924. enumerable: true,
  76925. configurable: true
  76926. });
  76927. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  76928. /**
  76929. * Get/set the maximum pitch angle that the bone can look to.
  76930. */
  76931. get: function () {
  76932. return this._maxPitch;
  76933. },
  76934. set: function (value) {
  76935. this._maxPitch = value;
  76936. this._maxPitchTan = Math.tan(value);
  76937. },
  76938. enumerable: true,
  76939. configurable: true
  76940. });
  76941. /**
  76942. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  76943. */
  76944. BoneLookController.prototype.update = function () {
  76945. //skip the first frame when slerping so that the mesh rotation is correct
  76946. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  76947. this._firstFrameSkipped = true;
  76948. return;
  76949. }
  76950. var bone = this.bone;
  76951. var bonePos = BoneLookController._tmpVecs[0];
  76952. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  76953. var target = this.target;
  76954. var _tmpMat1 = BoneLookController._tmpMats[0];
  76955. var _tmpMat2 = BoneLookController._tmpMats[1];
  76956. var mesh = this.mesh;
  76957. var parentBone = bone.getParent();
  76958. var upAxis = BoneLookController._tmpVecs[1];
  76959. upAxis.copyFrom(this.upAxis);
  76960. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  76961. if (this._transformYawPitch) {
  76962. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  76963. }
  76964. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  76965. }
  76966. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  76967. mesh.getDirectionToRef(upAxis, upAxis);
  76968. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  76969. upAxis.normalize();
  76970. }
  76971. }
  76972. var checkYaw = false;
  76973. var checkPitch = false;
  76974. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  76975. checkYaw = true;
  76976. }
  76977. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  76978. checkPitch = true;
  76979. }
  76980. if (checkYaw || checkPitch) {
  76981. var spaceMat = BoneLookController._tmpMats[2];
  76982. var spaceMatInv = BoneLookController._tmpMats[3];
  76983. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  76984. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  76985. }
  76986. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  76987. spaceMat.copyFrom(mesh.getWorldMatrix());
  76988. }
  76989. else {
  76990. var forwardAxis = BoneLookController._tmpVecs[2];
  76991. forwardAxis.copyFrom(this._fowardAxis);
  76992. if (this._transformYawPitch) {
  76993. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  76994. }
  76995. if (parentBone) {
  76996. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  76997. }
  76998. else {
  76999. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  77000. }
  77001. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  77002. rightAxis.normalize();
  77003. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  77004. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  77005. }
  77006. spaceMat.invertToRef(spaceMatInv);
  77007. var xzlen = null;
  77008. if (checkPitch) {
  77009. var localTarget = BoneLookController._tmpVecs[3];
  77010. target.subtractToRef(bonePos, localTarget);
  77011. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  77012. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77013. var pitch = Math.atan2(localTarget.y, xzlen);
  77014. var newPitch = pitch;
  77015. if (pitch > this._maxPitch) {
  77016. localTarget.y = this._maxPitchTan * xzlen;
  77017. newPitch = this._maxPitch;
  77018. }
  77019. else if (pitch < this._minPitch) {
  77020. localTarget.y = this._minPitchTan * xzlen;
  77021. newPitch = this._minPitch;
  77022. }
  77023. if (pitch != newPitch) {
  77024. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  77025. localTarget.addInPlace(bonePos);
  77026. target = localTarget;
  77027. }
  77028. }
  77029. if (checkYaw) {
  77030. var localTarget = BoneLookController._tmpVecs[4];
  77031. target.subtractToRef(bonePos, localTarget);
  77032. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  77033. var yaw = Math.atan2(localTarget.x, localTarget.z);
  77034. var newYaw = yaw;
  77035. if (yaw > this._maxYaw || yaw < this._minYaw) {
  77036. if (xzlen == null) {
  77037. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77038. }
  77039. if (this._yawRange > Math.PI) {
  77040. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  77041. localTarget.z = this._maxYawCos * xzlen;
  77042. localTarget.x = this._maxYawSin * xzlen;
  77043. newYaw = this._maxYaw;
  77044. }
  77045. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  77046. localTarget.z = this._minYawCos * xzlen;
  77047. localTarget.x = this._minYawSin * xzlen;
  77048. newYaw = this._minYaw;
  77049. }
  77050. }
  77051. else {
  77052. if (yaw > this._maxYaw) {
  77053. localTarget.z = this._maxYawCos * xzlen;
  77054. localTarget.x = this._maxYawSin * xzlen;
  77055. newYaw = this._maxYaw;
  77056. }
  77057. else if (yaw < this._minYaw) {
  77058. localTarget.z = this._minYawCos * xzlen;
  77059. localTarget.x = this._minYawSin * xzlen;
  77060. newYaw = this._minYaw;
  77061. }
  77062. }
  77063. }
  77064. if (this._slerping && this._yawRange > Math.PI) {
  77065. //are we going to be crossing into the min/max region?
  77066. var boneFwd = BoneLookController._tmpVecs[8];
  77067. boneFwd.copyFrom(BABYLON.Axis.Z);
  77068. if (this._transformYawPitch) {
  77069. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  77070. }
  77071. var boneRotMat = BoneLookController._tmpMats[4];
  77072. this._boneQuat.toRotationMatrix(boneRotMat);
  77073. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  77074. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  77075. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  77076. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  77077. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  77078. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  77079. if (angBtwTar > angBtwMidYaw) {
  77080. if (xzlen == null) {
  77081. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77082. }
  77083. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  77084. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  77085. if (angBtwMin < angBtwMax) {
  77086. newYaw = boneYaw + Math.PI * .75;
  77087. localTarget.z = Math.cos(newYaw) * xzlen;
  77088. localTarget.x = Math.sin(newYaw) * xzlen;
  77089. }
  77090. else {
  77091. newYaw = boneYaw - Math.PI * .75;
  77092. localTarget.z = Math.cos(newYaw) * xzlen;
  77093. localTarget.x = Math.sin(newYaw) * xzlen;
  77094. }
  77095. }
  77096. }
  77097. if (yaw != newYaw) {
  77098. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  77099. localTarget.addInPlace(bonePos);
  77100. target = localTarget;
  77101. }
  77102. }
  77103. }
  77104. var zaxis = BoneLookController._tmpVecs[5];
  77105. var xaxis = BoneLookController._tmpVecs[6];
  77106. var yaxis = BoneLookController._tmpVecs[7];
  77107. var _tmpQuat = BoneLookController._tmpQuat;
  77108. target.subtractToRef(bonePos, zaxis);
  77109. zaxis.normalize();
  77110. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  77111. xaxis.normalize();
  77112. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  77113. yaxis.normalize();
  77114. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  77115. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  77116. return;
  77117. }
  77118. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  77119. return;
  77120. }
  77121. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  77122. return;
  77123. }
  77124. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  77125. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  77126. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  77127. }
  77128. if (this.slerpAmount < 1) {
  77129. if (!this._slerping) {
  77130. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  77131. }
  77132. if (this._transformYawPitch) {
  77133. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  77134. }
  77135. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  77136. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  77137. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  77138. this._slerping = true;
  77139. }
  77140. else {
  77141. if (this._transformYawPitch) {
  77142. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  77143. }
  77144. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  77145. this._slerping = false;
  77146. }
  77147. };
  77148. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  77149. var angDiff = ang2 - ang1;
  77150. angDiff %= Math.PI * 2;
  77151. if (angDiff > Math.PI) {
  77152. angDiff -= Math.PI * 2;
  77153. }
  77154. else if (angDiff < -Math.PI) {
  77155. angDiff += Math.PI * 2;
  77156. }
  77157. return angDiff;
  77158. };
  77159. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  77160. ang1 %= (2 * Math.PI);
  77161. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  77162. ang2 %= (2 * Math.PI);
  77163. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  77164. var ab = 0;
  77165. if (ang1 < ang2) {
  77166. ab = ang2 - ang1;
  77167. }
  77168. else {
  77169. ab = ang1 - ang2;
  77170. }
  77171. if (ab > Math.PI) {
  77172. ab = Math.PI * 2 - ab;
  77173. }
  77174. return ab;
  77175. };
  77176. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  77177. ang %= (2 * Math.PI);
  77178. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  77179. ang1 %= (2 * Math.PI);
  77180. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  77181. ang2 %= (2 * Math.PI);
  77182. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  77183. if (ang1 < ang2) {
  77184. if (ang > ang1 && ang < ang2) {
  77185. return true;
  77186. }
  77187. }
  77188. else {
  77189. if (ang > ang2 && ang < ang1) {
  77190. return true;
  77191. }
  77192. }
  77193. return false;
  77194. };
  77195. 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()];
  77196. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  77197. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77198. return BoneLookController;
  77199. }());
  77200. BABYLON.BoneLookController = BoneLookController;
  77201. })(BABYLON || (BABYLON = {}));
  77202. //# sourceMappingURL=babylon.boneLookController.js.map
  77203. "use strict";
  77204. var BABYLON;
  77205. (function (BABYLON) {
  77206. var Skeleton = /** @class */ (function () {
  77207. function Skeleton(name, id, scene) {
  77208. this.name = name;
  77209. this.id = id;
  77210. this.bones = new Array();
  77211. this.needInitialSkinMatrix = false;
  77212. this._isDirty = true;
  77213. this._meshesWithPoseMatrix = new Array();
  77214. this._identity = BABYLON.Matrix.Identity();
  77215. this._ranges = {};
  77216. this._lastAbsoluteTransformsUpdateId = -1;
  77217. /**
  77218. * Specifies if the skeleton should be serialized.
  77219. */
  77220. this.doNotSerialize = false;
  77221. // Events
  77222. /**
  77223. * An event triggered before computing the skeleton's matrices
  77224. */
  77225. this.onBeforeComputeObservable = new BABYLON.Observable();
  77226. this.bones = [];
  77227. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77228. scene.skeletons.push(this);
  77229. //make sure it will recalculate the matrix next time prepare is called.
  77230. this._isDirty = true;
  77231. }
  77232. // Members
  77233. Skeleton.prototype.getTransformMatrices = function (mesh) {
  77234. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  77235. return mesh._bonesTransformMatrices;
  77236. }
  77237. if (!this._transformMatrices) {
  77238. this.prepare();
  77239. }
  77240. return this._transformMatrices;
  77241. };
  77242. Skeleton.prototype.getScene = function () {
  77243. return this._scene;
  77244. };
  77245. // Methods
  77246. /**
  77247. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  77248. */
  77249. Skeleton.prototype.toString = function (fullDetails) {
  77250. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  77251. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  77252. if (fullDetails) {
  77253. ret += ", Ranges: {";
  77254. var first = true;
  77255. for (var name_1 in this._ranges) {
  77256. if (first) {
  77257. ret += ", ";
  77258. first = false;
  77259. }
  77260. ret += name_1;
  77261. }
  77262. ret += "}";
  77263. }
  77264. return ret;
  77265. };
  77266. /**
  77267. * Get bone's index searching by name
  77268. * @param {string} name is bone's name to search for
  77269. * @return {number} Indice of the bone. Returns -1 if not found
  77270. */
  77271. Skeleton.prototype.getBoneIndexByName = function (name) {
  77272. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  77273. if (this.bones[boneIndex].name === name) {
  77274. return boneIndex;
  77275. }
  77276. }
  77277. return -1;
  77278. };
  77279. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  77280. // check name not already in use
  77281. if (!this._ranges[name]) {
  77282. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  77283. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77284. if (this.bones[i].animations[0]) {
  77285. this.bones[i].animations[0].createRange(name, from, to);
  77286. }
  77287. }
  77288. }
  77289. };
  77290. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  77291. if (deleteFrames === void 0) { deleteFrames = true; }
  77292. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77293. if (this.bones[i].animations[0]) {
  77294. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  77295. }
  77296. }
  77297. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  77298. };
  77299. Skeleton.prototype.getAnimationRange = function (name) {
  77300. return this._ranges[name];
  77301. };
  77302. /**
  77303. * Returns as an Array, all AnimationRanges defined on this skeleton
  77304. */
  77305. Skeleton.prototype.getAnimationRanges = function () {
  77306. var animationRanges = [];
  77307. var name;
  77308. var i = 0;
  77309. for (name in this._ranges) {
  77310. animationRanges[i] = this._ranges[name];
  77311. i++;
  77312. }
  77313. return animationRanges;
  77314. };
  77315. /**
  77316. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  77317. */
  77318. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  77319. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77320. if (this._ranges[name] || !source.getAnimationRange(name)) {
  77321. return false;
  77322. }
  77323. var ret = true;
  77324. var frameOffset = this._getHighestAnimationFrame() + 1;
  77325. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  77326. var boneDict = {};
  77327. var sourceBones = source.bones;
  77328. var nBones;
  77329. var i;
  77330. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  77331. boneDict[sourceBones[i].name] = sourceBones[i];
  77332. }
  77333. if (this.bones.length !== sourceBones.length) {
  77334. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  77335. ret = false;
  77336. }
  77337. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  77338. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  77339. var boneName = this.bones[i].name;
  77340. var sourceBone = boneDict[boneName];
  77341. if (sourceBone) {
  77342. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  77343. }
  77344. else {
  77345. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  77346. ret = false;
  77347. }
  77348. }
  77349. // do not call createAnimationRange(), since it also is done to bones, which was already done
  77350. var range = source.getAnimationRange(name);
  77351. if (range) {
  77352. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  77353. }
  77354. return ret;
  77355. };
  77356. Skeleton.prototype.returnToRest = function () {
  77357. for (var index = 0; index < this.bones.length; index++) {
  77358. this.bones[index].returnToRest();
  77359. }
  77360. };
  77361. Skeleton.prototype._getHighestAnimationFrame = function () {
  77362. var ret = 0;
  77363. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77364. if (this.bones[i].animations[0]) {
  77365. var highest = this.bones[i].animations[0].getHighestFrame();
  77366. if (ret < highest) {
  77367. ret = highest;
  77368. }
  77369. }
  77370. }
  77371. return ret;
  77372. };
  77373. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  77374. var range = this.getAnimationRange(name);
  77375. if (!range) {
  77376. return null;
  77377. }
  77378. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  77379. };
  77380. Skeleton.prototype._markAsDirty = function () {
  77381. this._isDirty = true;
  77382. };
  77383. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  77384. this._meshesWithPoseMatrix.push(mesh);
  77385. };
  77386. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  77387. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  77388. if (index > -1) {
  77389. this._meshesWithPoseMatrix.splice(index, 1);
  77390. }
  77391. };
  77392. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  77393. this.onBeforeComputeObservable.notifyObservers(this);
  77394. for (var index = 0; index < this.bones.length; index++) {
  77395. var bone = this.bones[index];
  77396. var parentBone = bone.getParent();
  77397. if (parentBone) {
  77398. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  77399. }
  77400. else {
  77401. if (initialSkinMatrix) {
  77402. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  77403. }
  77404. else {
  77405. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  77406. }
  77407. }
  77408. if (bone._index !== -1) {
  77409. var mappedIndex = bone._index === null ? index : bone._index;
  77410. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  77411. }
  77412. }
  77413. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  77414. };
  77415. Skeleton.prototype.prepare = function () {
  77416. if (!this._isDirty) {
  77417. return;
  77418. }
  77419. if (this.needInitialSkinMatrix) {
  77420. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  77421. var mesh = this._meshesWithPoseMatrix[index];
  77422. var poseMatrix = mesh.getPoseMatrix();
  77423. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  77424. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  77425. }
  77426. if (this._synchronizedWithMesh !== mesh) {
  77427. this._synchronizedWithMesh = mesh;
  77428. // Prepare bones
  77429. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  77430. var bone = this.bones[boneIndex];
  77431. if (!bone.getParent()) {
  77432. var matrix = bone.getBaseMatrix();
  77433. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  77434. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  77435. }
  77436. }
  77437. }
  77438. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  77439. }
  77440. }
  77441. else {
  77442. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  77443. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  77444. }
  77445. this._computeTransformMatrices(this._transformMatrices, null);
  77446. }
  77447. this._isDirty = false;
  77448. this._scene._activeBones.addCount(this.bones.length, false);
  77449. };
  77450. Skeleton.prototype.getAnimatables = function () {
  77451. if (!this._animatables || this._animatables.length !== this.bones.length) {
  77452. this._animatables = [];
  77453. for (var index = 0; index < this.bones.length; index++) {
  77454. this._animatables.push(this.bones[index]);
  77455. }
  77456. }
  77457. return this._animatables;
  77458. };
  77459. Skeleton.prototype.clone = function (name, id) {
  77460. var result = new Skeleton(name, id || name, this._scene);
  77461. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  77462. for (var index = 0; index < this.bones.length; index++) {
  77463. var source = this.bones[index];
  77464. var parentBone = null;
  77465. var parent_1 = source.getParent();
  77466. if (parent_1) {
  77467. var parentIndex = this.bones.indexOf(parent_1);
  77468. parentBone = result.bones[parentIndex];
  77469. }
  77470. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  77471. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  77472. }
  77473. if (this._ranges) {
  77474. result._ranges = {};
  77475. for (var rangeName in this._ranges) {
  77476. var range = this._ranges[rangeName];
  77477. if (range) {
  77478. result._ranges[rangeName] = range.clone();
  77479. }
  77480. }
  77481. }
  77482. this._isDirty = true;
  77483. return result;
  77484. };
  77485. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  77486. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  77487. this.bones.forEach(function (bone) {
  77488. bone.animations.forEach(function (animation) {
  77489. animation.enableBlending = true;
  77490. animation.blendingSpeed = blendingSpeed;
  77491. });
  77492. });
  77493. };
  77494. Skeleton.prototype.dispose = function () {
  77495. this._meshesWithPoseMatrix = [];
  77496. // Animations
  77497. this.getScene().stopAnimation(this);
  77498. // Remove from scene
  77499. this.getScene().removeSkeleton(this);
  77500. };
  77501. Skeleton.prototype.serialize = function () {
  77502. var serializationObject = {};
  77503. serializationObject.name = this.name;
  77504. serializationObject.id = this.id;
  77505. if (this.dimensionsAtRest) {
  77506. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  77507. }
  77508. serializationObject.bones = [];
  77509. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  77510. for (var index = 0; index < this.bones.length; index++) {
  77511. var bone = this.bones[index];
  77512. var parent_2 = bone.getParent();
  77513. var serializedBone = {
  77514. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  77515. name: bone.name,
  77516. matrix: bone.getBaseMatrix().toArray(),
  77517. rest: bone.getRestPose().toArray()
  77518. };
  77519. serializationObject.bones.push(serializedBone);
  77520. if (bone.length) {
  77521. serializedBone.length = bone.length;
  77522. }
  77523. if (bone.animations && bone.animations.length > 0) {
  77524. serializedBone.animation = bone.animations[0].serialize();
  77525. }
  77526. serializationObject.ranges = [];
  77527. for (var name in this._ranges) {
  77528. var source = this._ranges[name];
  77529. if (!source) {
  77530. continue;
  77531. }
  77532. var range = {};
  77533. range.name = name;
  77534. range.from = source.from;
  77535. range.to = source.to;
  77536. serializationObject.ranges.push(range);
  77537. }
  77538. }
  77539. return serializationObject;
  77540. };
  77541. Skeleton.Parse = function (parsedSkeleton, scene) {
  77542. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  77543. if (parsedSkeleton.dimensionsAtRest) {
  77544. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  77545. }
  77546. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  77547. var index;
  77548. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  77549. var parsedBone = parsedSkeleton.bones[index];
  77550. var parentBone = null;
  77551. if (parsedBone.parentBoneIndex > -1) {
  77552. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  77553. }
  77554. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  77555. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  77556. if (parsedBone.length) {
  77557. bone.length = parsedBone.length;
  77558. }
  77559. if (parsedBone.animation) {
  77560. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  77561. }
  77562. }
  77563. // placed after bones, so createAnimationRange can cascade down
  77564. if (parsedSkeleton.ranges) {
  77565. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  77566. var data = parsedSkeleton.ranges[index];
  77567. skeleton.createAnimationRange(data.name, data.from, data.to);
  77568. }
  77569. }
  77570. return skeleton;
  77571. };
  77572. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  77573. if (forceUpdate === void 0) { forceUpdate = false; }
  77574. var renderId = this._scene.getRenderId();
  77575. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  77576. this.bones[0].computeAbsoluteTransforms();
  77577. this._lastAbsoluteTransformsUpdateId = renderId;
  77578. }
  77579. };
  77580. Skeleton.prototype.getPoseMatrix = function () {
  77581. var poseMatrix = null;
  77582. if (this._meshesWithPoseMatrix.length > 0) {
  77583. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  77584. }
  77585. return poseMatrix;
  77586. };
  77587. Skeleton.prototype.sortBones = function () {
  77588. var bones = new Array();
  77589. var visited = new Array(this.bones.length);
  77590. for (var index = 0; index < this.bones.length; index++) {
  77591. this._sortBones(index, bones, visited);
  77592. }
  77593. this.bones = bones;
  77594. };
  77595. Skeleton.prototype._sortBones = function (index, bones, visited) {
  77596. if (visited[index]) {
  77597. return;
  77598. }
  77599. visited[index] = true;
  77600. var bone = this.bones[index];
  77601. if (bone._index === undefined) {
  77602. bone._index = index;
  77603. }
  77604. var parentBone = bone.getParent();
  77605. if (parentBone) {
  77606. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  77607. }
  77608. bones.push(bone);
  77609. };
  77610. return Skeleton;
  77611. }());
  77612. BABYLON.Skeleton = Skeleton;
  77613. })(BABYLON || (BABYLON = {}));
  77614. //# sourceMappingURL=babylon.skeleton.js.map
  77615. "use strict";
  77616. var BABYLON;
  77617. (function (BABYLON) {
  77618. var SphericalPolynomial = /** @class */ (function () {
  77619. function SphericalPolynomial() {
  77620. this.x = BABYLON.Vector3.Zero();
  77621. this.y = BABYLON.Vector3.Zero();
  77622. this.z = BABYLON.Vector3.Zero();
  77623. this.xx = BABYLON.Vector3.Zero();
  77624. this.yy = BABYLON.Vector3.Zero();
  77625. this.zz = BABYLON.Vector3.Zero();
  77626. this.xy = BABYLON.Vector3.Zero();
  77627. this.yz = BABYLON.Vector3.Zero();
  77628. this.zx = BABYLON.Vector3.Zero();
  77629. }
  77630. SphericalPolynomial.prototype.addAmbient = function (color) {
  77631. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77632. this.xx = this.xx.add(colorVector);
  77633. this.yy = this.yy.add(colorVector);
  77634. this.zz = this.zz.add(colorVector);
  77635. };
  77636. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  77637. var result = new SphericalPolynomial();
  77638. result.x = harmonics.L11.scale(1.02333);
  77639. result.y = harmonics.L1_1.scale(1.02333);
  77640. result.z = harmonics.L10.scale(1.02333);
  77641. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  77642. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  77643. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  77644. result.yz = harmonics.L2_1.scale(0.858086);
  77645. result.zx = harmonics.L21.scale(0.858086);
  77646. result.xy = harmonics.L2_2.scale(0.858086);
  77647. result.scale(1.0 / Math.PI);
  77648. return result;
  77649. };
  77650. SphericalPolynomial.prototype.scale = function (scale) {
  77651. this.x = this.x.scale(scale);
  77652. this.y = this.y.scale(scale);
  77653. this.z = this.z.scale(scale);
  77654. this.xx = this.xx.scale(scale);
  77655. this.yy = this.yy.scale(scale);
  77656. this.zz = this.zz.scale(scale);
  77657. this.yz = this.yz.scale(scale);
  77658. this.zx = this.zx.scale(scale);
  77659. this.xy = this.xy.scale(scale);
  77660. };
  77661. return SphericalPolynomial;
  77662. }());
  77663. BABYLON.SphericalPolynomial = SphericalPolynomial;
  77664. var SphericalHarmonics = /** @class */ (function () {
  77665. function SphericalHarmonics() {
  77666. this.L00 = BABYLON.Vector3.Zero();
  77667. this.L1_1 = BABYLON.Vector3.Zero();
  77668. this.L10 = BABYLON.Vector3.Zero();
  77669. this.L11 = BABYLON.Vector3.Zero();
  77670. this.L2_2 = BABYLON.Vector3.Zero();
  77671. this.L2_1 = BABYLON.Vector3.Zero();
  77672. this.L20 = BABYLON.Vector3.Zero();
  77673. this.L21 = BABYLON.Vector3.Zero();
  77674. this.L22 = BABYLON.Vector3.Zero();
  77675. }
  77676. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  77677. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77678. var c = colorVector.scale(deltaSolidAngle);
  77679. this.L00 = this.L00.add(c.scale(0.282095));
  77680. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  77681. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  77682. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  77683. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  77684. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  77685. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  77686. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  77687. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  77688. };
  77689. SphericalHarmonics.prototype.scale = function (scale) {
  77690. this.L00 = this.L00.scale(scale);
  77691. this.L1_1 = this.L1_1.scale(scale);
  77692. this.L10 = this.L10.scale(scale);
  77693. this.L11 = this.L11.scale(scale);
  77694. this.L2_2 = this.L2_2.scale(scale);
  77695. this.L2_1 = this.L2_1.scale(scale);
  77696. this.L20 = this.L20.scale(scale);
  77697. this.L21 = this.L21.scale(scale);
  77698. this.L22 = this.L22.scale(scale);
  77699. };
  77700. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  77701. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  77702. //
  77703. // E_lm = A_l * L_lm
  77704. //
  77705. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  77706. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  77707. // the scaling factors are given in equation 9.
  77708. // Constant (Band 0)
  77709. this.L00 = this.L00.scale(3.141593);
  77710. // Linear (Band 1)
  77711. this.L1_1 = this.L1_1.scale(2.094395);
  77712. this.L10 = this.L10.scale(2.094395);
  77713. this.L11 = this.L11.scale(2.094395);
  77714. // Quadratic (Band 2)
  77715. this.L2_2 = this.L2_2.scale(0.785398);
  77716. this.L2_1 = this.L2_1.scale(0.785398);
  77717. this.L20 = this.L20.scale(0.785398);
  77718. this.L21 = this.L21.scale(0.785398);
  77719. this.L22 = this.L22.scale(0.785398);
  77720. };
  77721. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  77722. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  77723. // L = (1/pi) * E * rho
  77724. //
  77725. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  77726. this.scale(1.0 / Math.PI);
  77727. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  77728. // (The pixel shader must apply albedo after texture fetches, etc).
  77729. };
  77730. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  77731. var result = new SphericalHarmonics();
  77732. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  77733. result.L1_1 = polynomial.y.scale(0.977204);
  77734. result.L10 = polynomial.z.scale(0.977204);
  77735. result.L11 = polynomial.x.scale(0.977204);
  77736. result.L2_2 = polynomial.xy.scale(1.16538);
  77737. result.L2_1 = polynomial.yz.scale(1.16538);
  77738. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  77739. result.L21 = polynomial.zx.scale(1.16538);
  77740. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  77741. result.scale(Math.PI);
  77742. return result;
  77743. };
  77744. return SphericalHarmonics;
  77745. }());
  77746. BABYLON.SphericalHarmonics = SphericalHarmonics;
  77747. })(BABYLON || (BABYLON = {}));
  77748. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  77749. "use strict";
  77750. var BABYLON;
  77751. (function (BABYLON) {
  77752. var FileFaceOrientation = /** @class */ (function () {
  77753. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  77754. this.name = name;
  77755. this.worldAxisForNormal = worldAxisForNormal;
  77756. this.worldAxisForFileX = worldAxisForFileX;
  77757. this.worldAxisForFileY = worldAxisForFileY;
  77758. }
  77759. return FileFaceOrientation;
  77760. }());
  77761. ;
  77762. /**
  77763. * Helper class dealing with the extraction of spherical polynomial dataArray
  77764. * from a cube map.
  77765. */
  77766. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  77767. function CubeMapToSphericalPolynomialTools() {
  77768. }
  77769. /**
  77770. * Converts a texture to the according Spherical Polynomial data.
  77771. * This extracts the first 3 orders only as they are the only one used in the lighting.
  77772. *
  77773. * @param texture The texture to extract the information from.
  77774. * @return The Spherical Polynomial data.
  77775. */
  77776. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  77777. if (!texture.isCube) {
  77778. // Only supports cube Textures currently.
  77779. return null;
  77780. }
  77781. var size = texture.getSize().width;
  77782. var right = texture.readPixels(0);
  77783. var left = texture.readPixels(1);
  77784. var up;
  77785. var down;
  77786. if (texture.isRenderTarget) {
  77787. up = texture.readPixels(3);
  77788. down = texture.readPixels(2);
  77789. }
  77790. else {
  77791. up = texture.readPixels(2);
  77792. down = texture.readPixels(3);
  77793. }
  77794. var front = texture.readPixels(4);
  77795. var back = texture.readPixels(5);
  77796. var gammaSpace = texture.gammaSpace;
  77797. // Always read as RGBA.
  77798. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  77799. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77800. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77801. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77802. }
  77803. var cubeInfo = {
  77804. size: size,
  77805. right: right,
  77806. left: left,
  77807. up: up,
  77808. down: down,
  77809. front: front,
  77810. back: back,
  77811. format: format,
  77812. type: type,
  77813. gammaSpace: gammaSpace,
  77814. };
  77815. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  77816. };
  77817. /**
  77818. * Converts a cubemap to the according Spherical Polynomial data.
  77819. * This extracts the first 3 orders only as they are the only one used in the lighting.
  77820. *
  77821. * @param cubeInfo The Cube map to extract the information from.
  77822. * @return The Spherical Polynomial data.
  77823. */
  77824. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  77825. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  77826. var totalSolidAngle = 0.0;
  77827. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  77828. var du = 2.0 / cubeInfo.size;
  77829. var dv = du;
  77830. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  77831. var minUV = du * 0.5 - 1.0;
  77832. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  77833. var fileFace = this.FileFaces[faceIndex];
  77834. var dataArray = cubeInfo[fileFace.name];
  77835. var v = minUV;
  77836. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  77837. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  77838. // Because SP is still linear, so summation is fine in that basis.
  77839. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  77840. for (var y = 0; y < cubeInfo.size; y++) {
  77841. var u = minUV;
  77842. for (var x = 0; x < cubeInfo.size; x++) {
  77843. // World direction (not normalised)
  77844. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  77845. worldDirection.normalize();
  77846. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  77847. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  77848. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  77849. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  77850. // Handle Integer types.
  77851. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77852. r /= 255;
  77853. g /= 255;
  77854. b /= 255;
  77855. }
  77856. // Handle Gamma space textures.
  77857. if (cubeInfo.gammaSpace) {
  77858. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  77859. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  77860. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  77861. }
  77862. var color = new BABYLON.Color3(r, g, b);
  77863. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  77864. totalSolidAngle += deltaSolidAngle;
  77865. u += du;
  77866. }
  77867. v += dv;
  77868. }
  77869. }
  77870. // Solid angle for entire sphere is 4*pi
  77871. var sphereSolidAngle = 4.0 * Math.PI;
  77872. // Adjust the solid angle to allow for how many faces we processed.
  77873. var facesProcessed = 6.0;
  77874. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  77875. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  77876. // This is needed because the numerical integration over the cube uses a
  77877. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  77878. // and also to compensate for accumulative error due to float precision in the summation.
  77879. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  77880. sphericalHarmonics.scale(correctionFactor);
  77881. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  77882. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  77883. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  77884. };
  77885. CubeMapToSphericalPolynomialTools.FileFaces = [
  77886. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  77887. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  77888. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  77889. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  77890. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  77891. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  77892. ];
  77893. return CubeMapToSphericalPolynomialTools;
  77894. }());
  77895. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  77896. })(BABYLON || (BABYLON = {}));
  77897. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  77898. "use strict";
  77899. var BABYLON;
  77900. (function (BABYLON) {
  77901. /**
  77902. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  77903. */
  77904. var PanoramaToCubeMapTools = /** @class */ (function () {
  77905. function PanoramaToCubeMapTools() {
  77906. }
  77907. /**
  77908. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  77909. *
  77910. * @param float32Array The source data.
  77911. * @param inputWidth The width of the input panorama.
  77912. * @param inputhHeight The height of the input panorama.
  77913. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  77914. * @return The cubemap data
  77915. */
  77916. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  77917. if (!float32Array) {
  77918. throw "ConvertPanoramaToCubemap: input cannot be null";
  77919. }
  77920. if (float32Array.length != inputWidth * inputHeight * 3) {
  77921. throw "ConvertPanoramaToCubemap: input size is wrong";
  77922. }
  77923. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  77924. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  77925. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  77926. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  77927. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  77928. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  77929. return {
  77930. front: textureFront,
  77931. back: textureBack,
  77932. left: textureLeft,
  77933. right: textureRight,
  77934. up: textureUp,
  77935. down: textureDown,
  77936. size: size,
  77937. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  77938. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  77939. gammaSpace: false,
  77940. };
  77941. };
  77942. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  77943. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  77944. var textureArray = new Float32Array(buffer);
  77945. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  77946. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  77947. var dy = 1 / texSize;
  77948. var fy = 0;
  77949. for (var y = 0; y < texSize; y++) {
  77950. var xv1 = faceData[0];
  77951. var xv2 = faceData[2];
  77952. for (var x = 0; x < texSize; x++) {
  77953. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  77954. v.normalize();
  77955. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  77956. // 3 channels per pixels
  77957. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  77958. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  77959. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  77960. xv1 = xv1.add(rotDX1);
  77961. xv2 = xv2.add(rotDX2);
  77962. }
  77963. fy += dy;
  77964. }
  77965. return textureArray;
  77966. };
  77967. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  77968. var theta = Math.atan2(vDir.z, vDir.x);
  77969. var phi = Math.acos(vDir.y);
  77970. while (theta < -Math.PI)
  77971. theta += 2 * Math.PI;
  77972. while (theta > Math.PI)
  77973. theta -= 2 * Math.PI;
  77974. var dx = theta / Math.PI;
  77975. var dy = phi / Math.PI;
  77976. // recenter.
  77977. dx = dx * 0.5 + 0.5;
  77978. var px = Math.round(dx * inputWidth);
  77979. if (px < 0)
  77980. px = 0;
  77981. else if (px >= inputWidth)
  77982. px = inputWidth - 1;
  77983. var py = Math.round(dy * inputHeight);
  77984. if (py < 0)
  77985. py = 0;
  77986. else if (py >= inputHeight)
  77987. py = inputHeight - 1;
  77988. var inputY = (inputHeight - py - 1);
  77989. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  77990. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  77991. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  77992. return {
  77993. r: r,
  77994. g: g,
  77995. b: b
  77996. };
  77997. };
  77998. PanoramaToCubeMapTools.FACE_FRONT = [
  77999. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78000. new BABYLON.Vector3(1.0, -1.0, -1.0),
  78001. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  78002. new BABYLON.Vector3(1.0, 1.0, -1.0)
  78003. ];
  78004. PanoramaToCubeMapTools.FACE_BACK = [
  78005. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78006. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78007. new BABYLON.Vector3(1.0, 1.0, 1.0),
  78008. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  78009. ];
  78010. PanoramaToCubeMapTools.FACE_RIGHT = [
  78011. new BABYLON.Vector3(1.0, -1.0, -1.0),
  78012. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78013. new BABYLON.Vector3(1.0, 1.0, -1.0),
  78014. new BABYLON.Vector3(1.0, 1.0, 1.0)
  78015. ];
  78016. PanoramaToCubeMapTools.FACE_LEFT = [
  78017. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78018. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78019. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  78020. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  78021. ];
  78022. PanoramaToCubeMapTools.FACE_DOWN = [
  78023. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  78024. new BABYLON.Vector3(1.0, 1.0, -1.0),
  78025. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  78026. new BABYLON.Vector3(1.0, 1.0, 1.0)
  78027. ];
  78028. PanoramaToCubeMapTools.FACE_UP = [
  78029. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78030. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78031. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78032. new BABYLON.Vector3(1.0, -1.0, -1.0)
  78033. ];
  78034. return PanoramaToCubeMapTools;
  78035. }());
  78036. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  78037. })(BABYLON || (BABYLON = {}));
  78038. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  78039. "use strict";
  78040. var BABYLON;
  78041. (function (BABYLON) {
  78042. ;
  78043. /**
  78044. * This groups tools to convert HDR texture to native colors array.
  78045. */
  78046. var HDRTools = /** @class */ (function () {
  78047. function HDRTools() {
  78048. }
  78049. HDRTools.Ldexp = function (mantissa, exponent) {
  78050. if (exponent > 1023) {
  78051. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  78052. }
  78053. if (exponent < -1074) {
  78054. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  78055. }
  78056. return mantissa * Math.pow(2, exponent);
  78057. };
  78058. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  78059. if (exponent > 0) {
  78060. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  78061. float32array[index + 0] = red * exponent;
  78062. float32array[index + 1] = green * exponent;
  78063. float32array[index + 2] = blue * exponent;
  78064. }
  78065. else {
  78066. float32array[index + 0] = 0;
  78067. float32array[index + 1] = 0;
  78068. float32array[index + 2] = 0;
  78069. }
  78070. };
  78071. HDRTools.readStringLine = function (uint8array, startIndex) {
  78072. var line = "";
  78073. var character = "";
  78074. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  78075. character = String.fromCharCode(uint8array[i]);
  78076. if (character == "\n") {
  78077. break;
  78078. }
  78079. line += character;
  78080. }
  78081. return line;
  78082. };
  78083. /**
  78084. * Reads header information from an RGBE texture stored in a native array.
  78085. * More information on this format are available here:
  78086. * https://en.wikipedia.org/wiki/RGBE_image_format
  78087. *
  78088. * @param uint8array The binary file stored in native array.
  78089. * @return The header information.
  78090. */
  78091. HDRTools.RGBE_ReadHeader = function (uint8array) {
  78092. var height = 0;
  78093. var width = 0;
  78094. var line = this.readStringLine(uint8array, 0);
  78095. if (line[0] != '#' || line[1] != '?') {
  78096. throw "Bad HDR Format.";
  78097. }
  78098. var endOfHeader = false;
  78099. var findFormat = false;
  78100. var lineIndex = 0;
  78101. do {
  78102. lineIndex += (line.length + 1);
  78103. line = this.readStringLine(uint8array, lineIndex);
  78104. if (line == "FORMAT=32-bit_rle_rgbe") {
  78105. findFormat = true;
  78106. }
  78107. else if (line.length == 0) {
  78108. endOfHeader = true;
  78109. }
  78110. } while (!endOfHeader);
  78111. if (!findFormat) {
  78112. throw "HDR Bad header format, unsupported FORMAT";
  78113. }
  78114. lineIndex += (line.length + 1);
  78115. line = this.readStringLine(uint8array, lineIndex);
  78116. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  78117. var match = sizeRegexp.exec(line);
  78118. // TODO. Support +Y and -X if needed.
  78119. if (!match || match.length < 3) {
  78120. throw "HDR Bad header format, no size";
  78121. }
  78122. width = parseInt(match[2]);
  78123. height = parseInt(match[1]);
  78124. if (width < 8 || width > 0x7fff) {
  78125. throw "HDR Bad header format, unsupported size";
  78126. }
  78127. lineIndex += (line.length + 1);
  78128. return {
  78129. height: height,
  78130. width: width,
  78131. dataPosition: lineIndex
  78132. };
  78133. };
  78134. /**
  78135. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  78136. * This RGBE texture needs to store the information as a panorama.
  78137. *
  78138. * More information on this format are available here:
  78139. * https://en.wikipedia.org/wiki/RGBE_image_format
  78140. *
  78141. * @param buffer The binary file stored in an array buffer.
  78142. * @param size The expected size of the extracted cubemap.
  78143. * @return The Cube Map information.
  78144. */
  78145. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  78146. var uint8array = new Uint8Array(buffer);
  78147. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  78148. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  78149. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  78150. return cubeMapData;
  78151. };
  78152. /**
  78153. * Returns the pixels data extracted from an RGBE texture.
  78154. * This pixels will be stored left to right up to down in the R G B order in one array.
  78155. *
  78156. * More information on this format are available here:
  78157. * https://en.wikipedia.org/wiki/RGBE_image_format
  78158. *
  78159. * @param uint8array The binary file stored in an array buffer.
  78160. * @param hdrInfo The header information of the file.
  78161. * @return The pixels data in RGB right to left up to down order.
  78162. */
  78163. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  78164. // Keep for multi format supports.
  78165. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  78166. };
  78167. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  78168. var num_scanlines = hdrInfo.height;
  78169. var scanline_width = hdrInfo.width;
  78170. var a, b, c, d, count;
  78171. var dataIndex = hdrInfo.dataPosition;
  78172. var index = 0, endIndex = 0, i = 0;
  78173. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  78174. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  78175. // 3 channels of 4 bytes per pixel in float.
  78176. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  78177. var resultArray = new Float32Array(resultBuffer);
  78178. // read in each successive scanline
  78179. while (num_scanlines > 0) {
  78180. a = uint8array[dataIndex++];
  78181. b = uint8array[dataIndex++];
  78182. c = uint8array[dataIndex++];
  78183. d = uint8array[dataIndex++];
  78184. if (a != 2 || b != 2 || (c & 0x80)) {
  78185. // this file is not run length encoded
  78186. throw "HDR Bad header format, not RLE";
  78187. }
  78188. if (((c << 8) | d) != scanline_width) {
  78189. throw "HDR Bad header format, wrong scan line width";
  78190. }
  78191. index = 0;
  78192. // read each of the four channels for the scanline into the buffer
  78193. for (i = 0; i < 4; i++) {
  78194. endIndex = (i + 1) * scanline_width;
  78195. while (index < endIndex) {
  78196. a = uint8array[dataIndex++];
  78197. b = uint8array[dataIndex++];
  78198. if (a > 128) {
  78199. // a run of the same value
  78200. count = a - 128;
  78201. if ((count == 0) || (count > endIndex - index)) {
  78202. throw "HDR Bad Format, bad scanline data (run)";
  78203. }
  78204. while (count-- > 0) {
  78205. scanLineArray[index++] = b;
  78206. }
  78207. }
  78208. else {
  78209. // a non-run
  78210. count = a;
  78211. if ((count == 0) || (count > endIndex - index)) {
  78212. throw "HDR Bad Format, bad scanline data (non-run)";
  78213. }
  78214. scanLineArray[index++] = b;
  78215. if (--count > 0) {
  78216. for (var j = 0; j < count; j++) {
  78217. scanLineArray[index++] = uint8array[dataIndex++];
  78218. }
  78219. }
  78220. }
  78221. }
  78222. }
  78223. // now convert data from buffer into floats
  78224. for (i = 0; i < scanline_width; i++) {
  78225. a = scanLineArray[i];
  78226. b = scanLineArray[i + scanline_width];
  78227. c = scanLineArray[i + 2 * scanline_width];
  78228. d = scanLineArray[i + 3 * scanline_width];
  78229. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  78230. }
  78231. num_scanlines--;
  78232. }
  78233. return resultArray;
  78234. };
  78235. return HDRTools;
  78236. }());
  78237. BABYLON.HDRTools = HDRTools;
  78238. })(BABYLON || (BABYLON = {}));
  78239. //# sourceMappingURL=babylon.hdr.js.map
  78240. "use strict";
  78241. var BABYLON;
  78242. (function (BABYLON) {
  78243. /**
  78244. * This represents a texture coming from an HDR input.
  78245. *
  78246. * The only supported format is currently panorama picture stored in RGBE format.
  78247. * Example of such files can be found on HDRLib: http://hdrlib.com/
  78248. */
  78249. var HDRCubeTexture = /** @class */ (function (_super) {
  78250. __extends(HDRCubeTexture, _super);
  78251. /**
  78252. * Instantiates an HDRTexture from the following parameters.
  78253. *
  78254. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  78255. * @param scene The scene the texture will be used in
  78256. * @param size The cubemap 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.
  78257. * @param noMipmap Forces to not generate the mipmap if true
  78258. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  78259. * @param useInGammaSpace 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)
  78260. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  78261. */
  78262. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  78263. if (noMipmap === void 0) { noMipmap = false; }
  78264. if (generateHarmonics === void 0) { generateHarmonics = true; }
  78265. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  78266. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  78267. if (onLoad === void 0) { onLoad = null; }
  78268. if (onError === void 0) { onError = null; }
  78269. var _this = _super.call(this, scene) || this;
  78270. _this._useInGammaSpace = false;
  78271. _this._generateHarmonics = true;
  78272. _this._isBABYLONPreprocessed = false;
  78273. _this._onLoad = null;
  78274. _this._onError = null;
  78275. /**
  78276. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  78277. */
  78278. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  78279. /**
  78280. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  78281. * This is usefull at run time to apply the good shader.
  78282. */
  78283. _this.isPMREM = false;
  78284. _this._isBlocking = true;
  78285. _this._rotationY = 0;
  78286. /**
  78287. * Gets or sets the center of the bounding box associated with the cube texture
  78288. * It must define where the camera used to render the texture was set
  78289. */
  78290. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  78291. if (!url) {
  78292. return _this;
  78293. }
  78294. _this.name = url;
  78295. _this.url = url;
  78296. _this.hasAlpha = false;
  78297. _this.isCube = true;
  78298. _this._textureMatrix = BABYLON.Matrix.Identity();
  78299. _this._onLoad = onLoad;
  78300. _this._onError = onError;
  78301. _this.gammaSpace = false;
  78302. var caps = scene.getEngine().getCaps();
  78303. if (size) {
  78304. _this._isBABYLONPreprocessed = false;
  78305. _this._noMipmap = noMipmap;
  78306. _this._size = size;
  78307. _this._useInGammaSpace = useInGammaSpace;
  78308. _this._usePMREMGenerator = usePMREMGenerator &&
  78309. caps.textureLOD &&
  78310. caps.textureFloat &&
  78311. !_this._useInGammaSpace;
  78312. }
  78313. else {
  78314. _this._isBABYLONPreprocessed = true;
  78315. _this._noMipmap = false;
  78316. _this._useInGammaSpace = false;
  78317. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  78318. !_this._useInGammaSpace;
  78319. }
  78320. _this.isPMREM = _this._usePMREMGenerator;
  78321. _this._texture = _this._getFromCache(url, _this._noMipmap);
  78322. if (!_this._texture) {
  78323. if (!scene.useDelayedTextureLoading) {
  78324. _this.loadTexture();
  78325. }
  78326. else {
  78327. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  78328. }
  78329. }
  78330. return _this;
  78331. }
  78332. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  78333. /**
  78334. * Gets wether or not the texture is blocking during loading.
  78335. */
  78336. get: function () {
  78337. return this._isBlocking;
  78338. },
  78339. /**
  78340. * Sets wether or not the texture is blocking during loading.
  78341. */
  78342. set: function (value) {
  78343. this._isBlocking = value;
  78344. },
  78345. enumerable: true,
  78346. configurable: true
  78347. });
  78348. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  78349. /**
  78350. * Gets texture matrix rotation angle around Y axis radians.
  78351. */
  78352. get: function () {
  78353. return this._rotationY;
  78354. },
  78355. /**
  78356. * Sets texture matrix rotation angle around Y axis in radians.
  78357. */
  78358. set: function (value) {
  78359. this._rotationY = value;
  78360. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  78361. },
  78362. enumerable: true,
  78363. configurable: true
  78364. });
  78365. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  78366. get: function () {
  78367. return this._boundingBoxSize;
  78368. },
  78369. /**
  78370. * Gets or sets the size of the bounding box associated with the cube texture
  78371. * When defined, the cubemap will switch to local mode
  78372. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  78373. * @example https://www.babylonjs-playground.com/#RNASML
  78374. */
  78375. set: function (value) {
  78376. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  78377. return;
  78378. }
  78379. this._boundingBoxSize = value;
  78380. var scene = this.getScene();
  78381. if (scene) {
  78382. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  78383. }
  78384. },
  78385. enumerable: true,
  78386. configurable: true
  78387. });
  78388. /**
  78389. * Occurs when the file is a preprocessed .babylon.hdr file.
  78390. */
  78391. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  78392. var _this = this;
  78393. var mipLevels = 0;
  78394. var floatArrayView = null;
  78395. var scene = this.getScene();
  78396. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  78397. var mips = new Array();
  78398. if (!floatArrayView) {
  78399. return mips;
  78400. }
  78401. var startIndex = 30;
  78402. for (var level = 0; level < mipLevels; level++) {
  78403. mips.push([]);
  78404. // Fill each pixel of the mip level.
  78405. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  78406. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78407. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  78408. mips[level].push(faceData);
  78409. startIndex += faceSize;
  78410. }
  78411. }
  78412. return mips;
  78413. } : null;
  78414. var callback = function (buffer) {
  78415. var scene = _this.getScene();
  78416. if (!scene) {
  78417. return null;
  78418. }
  78419. // Create Native Array Views
  78420. var intArrayView = new Int32Array(buffer);
  78421. floatArrayView = new Float32Array(buffer);
  78422. // Fill header.
  78423. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  78424. _this._size = intArrayView[1]; // CubeMap max mip face size.
  78425. // Update Texture Information.
  78426. if (!_this._texture) {
  78427. return null;
  78428. }
  78429. _this._texture.updateSize(_this._size, _this._size);
  78430. // Fill polynomial information.
  78431. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  78432. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  78433. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  78434. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  78435. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  78436. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  78437. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  78438. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  78439. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  78440. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  78441. _this.sphericalPolynomial = sphericalPolynomial;
  78442. // Fill pixel data.
  78443. mipLevels = intArrayView[29]; // Number of mip levels.
  78444. var startIndex = 30;
  78445. var data = [];
  78446. var faceSize = Math.pow(_this._size, 2) * 3;
  78447. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78448. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  78449. startIndex += faceSize;
  78450. }
  78451. var results = [];
  78452. var byteArray = null;
  78453. // Push each faces.
  78454. for (var k = 0; k < 6; k++) {
  78455. var dataFace = null;
  78456. // To be deprecated.
  78457. if (version === 1) {
  78458. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  78459. dataFace = data[j];
  78460. }
  78461. // If special cases.
  78462. if (!mipmapGenerator && dataFace) {
  78463. if (!scene.getEngine().getCaps().textureFloat) {
  78464. // 3 channels of 1 bytes per pixel in bytes.
  78465. var byteBuffer = new ArrayBuffer(faceSize);
  78466. byteArray = new Uint8Array(byteBuffer);
  78467. }
  78468. for (var i = 0; i < _this._size * _this._size; i++) {
  78469. // Put in gamma space if requested.
  78470. if (_this._useInGammaSpace) {
  78471. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  78472. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  78473. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  78474. }
  78475. // Convert to int texture for fallback.
  78476. if (byteArray) {
  78477. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  78478. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  78479. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  78480. // May use luminance instead if the result is not accurate.
  78481. var max = Math.max(Math.max(r, g), b);
  78482. if (max > 255) {
  78483. var scale = 255 / max;
  78484. r *= scale;
  78485. g *= scale;
  78486. b *= scale;
  78487. }
  78488. byteArray[(i * 3) + 0] = r;
  78489. byteArray[(i * 3) + 1] = g;
  78490. byteArray[(i * 3) + 2] = b;
  78491. }
  78492. }
  78493. }
  78494. // Fill the array accordingly.
  78495. if (byteArray) {
  78496. results.push(byteArray);
  78497. }
  78498. else {
  78499. results.push(dataFace);
  78500. }
  78501. }
  78502. return results;
  78503. };
  78504. if (scene) {
  78505. 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, mipmapGenerator, this._onLoad, this._onError);
  78506. }
  78507. };
  78508. /**
  78509. * Occurs when the file is raw .hdr file.
  78510. */
  78511. HDRCubeTexture.prototype.loadHDRTexture = function () {
  78512. var _this = this;
  78513. var callback = function (buffer) {
  78514. var scene = _this.getScene();
  78515. if (!scene) {
  78516. return null;
  78517. }
  78518. // Extract the raw linear data.
  78519. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  78520. // Generate harmonics if needed.
  78521. if (_this._generateHarmonics) {
  78522. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  78523. _this.sphericalPolynomial = sphericalPolynomial;
  78524. }
  78525. var results = [];
  78526. var byteArray = null;
  78527. // Push each faces.
  78528. for (var j = 0; j < 6; j++) {
  78529. // Create uintarray fallback.
  78530. if (!scene.getEngine().getCaps().textureFloat) {
  78531. // 3 channels of 1 bytes per pixel in bytes.
  78532. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  78533. byteArray = new Uint8Array(byteBuffer);
  78534. }
  78535. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  78536. // If special cases.
  78537. if (_this._useInGammaSpace || byteArray) {
  78538. for (var i = 0; i < _this._size * _this._size; i++) {
  78539. // Put in gamma space if requested.
  78540. if (_this._useInGammaSpace) {
  78541. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  78542. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  78543. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  78544. }
  78545. // Convert to int texture for fallback.
  78546. if (byteArray) {
  78547. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  78548. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  78549. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  78550. // May use luminance instead if the result is not accurate.
  78551. var max = Math.max(Math.max(r, g), b);
  78552. if (max > 255) {
  78553. var scale = 255 / max;
  78554. r *= scale;
  78555. g *= scale;
  78556. b *= scale;
  78557. }
  78558. byteArray[(i * 3) + 0] = r;
  78559. byteArray[(i * 3) + 1] = g;
  78560. byteArray[(i * 3) + 2] = b;
  78561. }
  78562. }
  78563. }
  78564. if (byteArray) {
  78565. results.push(byteArray);
  78566. }
  78567. else {
  78568. results.push(dataFace);
  78569. }
  78570. }
  78571. return results;
  78572. };
  78573. var mipmapGenerator = null;
  78574. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  78575. // if (!this._noMipmap &&
  78576. // this._usePMREMGenerator) {
  78577. // mipmapGenerator = (data: ArrayBufferView[]) => {
  78578. // // Custom setup of the generator matching with the PBR shader values.
  78579. // var generator = new BABYLON.PMREMGenerator(data,
  78580. // this._size,
  78581. // this._size,
  78582. // 0,
  78583. // 3,
  78584. // this.getScene().getEngine().getCaps().textureFloat,
  78585. // 2048,
  78586. // 0.25,
  78587. // false,
  78588. // true);
  78589. // return generator.filterCubeMap();
  78590. // };
  78591. // }
  78592. var scene = this.getScene();
  78593. if (scene) {
  78594. 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, mipmapGenerator, this._onLoad, this._onError);
  78595. }
  78596. };
  78597. /**
  78598. * Starts the loading process of the texture.
  78599. */
  78600. HDRCubeTexture.prototype.loadTexture = function () {
  78601. if (this._isBABYLONPreprocessed) {
  78602. this.loadBabylonTexture();
  78603. }
  78604. else {
  78605. this.loadHDRTexture();
  78606. }
  78607. };
  78608. HDRCubeTexture.prototype.clone = function () {
  78609. var scene = this.getScene();
  78610. if (!scene) {
  78611. return this;
  78612. }
  78613. var size = (this._isBABYLONPreprocessed ? null : this._size);
  78614. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  78615. // Base texture
  78616. newTexture.level = this.level;
  78617. newTexture.wrapU = this.wrapU;
  78618. newTexture.wrapV = this.wrapV;
  78619. newTexture.coordinatesIndex = this.coordinatesIndex;
  78620. newTexture.coordinatesMode = this.coordinatesMode;
  78621. return newTexture;
  78622. };
  78623. // Methods
  78624. HDRCubeTexture.prototype.delayLoad = function () {
  78625. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78626. return;
  78627. }
  78628. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78629. this._texture = this._getFromCache(this.url, this._noMipmap);
  78630. if (!this._texture) {
  78631. this.loadTexture();
  78632. }
  78633. };
  78634. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  78635. return this._textureMatrix;
  78636. };
  78637. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  78638. this._textureMatrix = value;
  78639. };
  78640. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78641. var texture = null;
  78642. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78643. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  78644. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  78645. texture.name = parsedTexture.name;
  78646. texture.hasAlpha = parsedTexture.hasAlpha;
  78647. texture.level = parsedTexture.level;
  78648. texture.coordinatesMode = parsedTexture.coordinatesMode;
  78649. texture.isBlocking = parsedTexture.isBlocking;
  78650. }
  78651. if (texture) {
  78652. if (parsedTexture.boundingBoxPosition) {
  78653. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  78654. }
  78655. if (parsedTexture.boundingBoxSize) {
  78656. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  78657. }
  78658. if (parsedTexture.rotationY) {
  78659. texture.rotationY = parsedTexture.rotationY;
  78660. }
  78661. }
  78662. return texture;
  78663. };
  78664. HDRCubeTexture.prototype.serialize = function () {
  78665. if (!this.name) {
  78666. return null;
  78667. }
  78668. var serializationObject = {};
  78669. serializationObject.name = this.name;
  78670. serializationObject.hasAlpha = this.hasAlpha;
  78671. serializationObject.isCube = true;
  78672. serializationObject.level = this.level;
  78673. serializationObject.size = this._size;
  78674. serializationObject.coordinatesMode = this.coordinatesMode;
  78675. serializationObject.useInGammaSpace = this._useInGammaSpace;
  78676. serializationObject.generateHarmonics = this._generateHarmonics;
  78677. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  78678. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  78679. serializationObject.customType = "BABYLON.HDRCubeTexture";
  78680. serializationObject.noMipmap = this._noMipmap;
  78681. serializationObject.isBlocking = this._isBlocking;
  78682. serializationObject.rotationY = this._rotationY;
  78683. return serializationObject;
  78684. };
  78685. /**
  78686. * Saves as a file the data contained in the texture in a binary format.
  78687. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  78688. * as the spherical used in the lighting.
  78689. * @param url The HDR file url.
  78690. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  78691. * @param onError Method called if any error happens during download.
  78692. * @return The packed binary data.
  78693. */
  78694. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  78695. if (onError === void 0) { onError = null; }
  78696. var callback = function (buffer) {
  78697. var data = new Blob([buffer], { type: 'application/octet-stream' });
  78698. // Returns a URL you can use as a href.
  78699. var objUrl = window.URL.createObjectURL(data);
  78700. // Simulates a link to it and click to dowload.
  78701. var a = document.createElement("a");
  78702. document.body.appendChild(a);
  78703. a.style.display = "none";
  78704. a.href = objUrl;
  78705. a.download = "envmap.babylon.hdr";
  78706. a.click();
  78707. };
  78708. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  78709. };
  78710. /**
  78711. * Serializes the data contained in the texture in a binary format.
  78712. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  78713. * as the spherical used in the lighting.
  78714. * @param url The HDR file url.
  78715. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  78716. * @param onError Method called if any error happens during download.
  78717. * @return The packed binary data.
  78718. */
  78719. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  78720. if (onError === void 0) { onError = null; }
  78721. // Needs the url tho create the texture.
  78722. if (!url) {
  78723. return;
  78724. }
  78725. // Check Power of two size.
  78726. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  78727. return;
  78728. }
  78729. // Coming Back in 3.x.
  78730. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  78731. };
  78732. HDRCubeTexture._facesMapping = [
  78733. "right",
  78734. "left",
  78735. "up",
  78736. "down",
  78737. "front",
  78738. "back"
  78739. ];
  78740. return HDRCubeTexture;
  78741. }(BABYLON.BaseTexture));
  78742. BABYLON.HDRCubeTexture = HDRCubeTexture;
  78743. })(BABYLON || (BABYLON = {}));
  78744. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  78745. "use strict";
  78746. var BABYLON;
  78747. (function (BABYLON) {
  78748. var IndexedVector2 = /** @class */ (function (_super) {
  78749. __extends(IndexedVector2, _super);
  78750. function IndexedVector2(original, index) {
  78751. var _this = _super.call(this, original.x, original.y) || this;
  78752. _this.index = index;
  78753. return _this;
  78754. }
  78755. return IndexedVector2;
  78756. }(BABYLON.Vector2));
  78757. var PolygonPoints = /** @class */ (function () {
  78758. function PolygonPoints() {
  78759. this.elements = new Array();
  78760. }
  78761. PolygonPoints.prototype.add = function (originalPoints) {
  78762. var _this = this;
  78763. var result = new Array();
  78764. originalPoints.forEach(function (point) {
  78765. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  78766. var newPoint = new IndexedVector2(point, _this.elements.length);
  78767. result.push(newPoint);
  78768. _this.elements.push(newPoint);
  78769. }
  78770. });
  78771. return result;
  78772. };
  78773. PolygonPoints.prototype.computeBounds = function () {
  78774. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  78775. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  78776. this.elements.forEach(function (point) {
  78777. // x
  78778. if (point.x < lmin.x) {
  78779. lmin.x = point.x;
  78780. }
  78781. else if (point.x > lmax.x) {
  78782. lmax.x = point.x;
  78783. }
  78784. // y
  78785. if (point.y < lmin.y) {
  78786. lmin.y = point.y;
  78787. }
  78788. else if (point.y > lmax.y) {
  78789. lmax.y = point.y;
  78790. }
  78791. });
  78792. return {
  78793. min: lmin,
  78794. max: lmax,
  78795. width: lmax.x - lmin.x,
  78796. height: lmax.y - lmin.y
  78797. };
  78798. };
  78799. return PolygonPoints;
  78800. }());
  78801. var Polygon = /** @class */ (function () {
  78802. function Polygon() {
  78803. }
  78804. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  78805. return [
  78806. new BABYLON.Vector2(xmin, ymin),
  78807. new BABYLON.Vector2(xmax, ymin),
  78808. new BABYLON.Vector2(xmax, ymax),
  78809. new BABYLON.Vector2(xmin, ymax)
  78810. ];
  78811. };
  78812. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  78813. if (cx === void 0) { cx = 0; }
  78814. if (cy === void 0) { cy = 0; }
  78815. if (numberOfSides === void 0) { numberOfSides = 32; }
  78816. var result = new Array();
  78817. var angle = 0;
  78818. var increment = (Math.PI * 2) / numberOfSides;
  78819. for (var i = 0; i < numberOfSides; i++) {
  78820. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  78821. angle -= increment;
  78822. }
  78823. return result;
  78824. };
  78825. Polygon.Parse = function (input) {
  78826. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  78827. var i, result = [];
  78828. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  78829. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  78830. }
  78831. return result;
  78832. };
  78833. Polygon.StartingAt = function (x, y) {
  78834. return BABYLON.Path2.StartingAt(x, y);
  78835. };
  78836. return Polygon;
  78837. }());
  78838. BABYLON.Polygon = Polygon;
  78839. var PolygonMeshBuilder = /** @class */ (function () {
  78840. function PolygonMeshBuilder(name, contours, scene) {
  78841. this._points = new PolygonPoints();
  78842. this._outlinepoints = new PolygonPoints();
  78843. this._holes = new Array();
  78844. this._epoints = new Array();
  78845. this._eholes = new Array();
  78846. this._name = name;
  78847. this._scene = scene;
  78848. var points;
  78849. if (contours instanceof BABYLON.Path2) {
  78850. points = contours.getPoints();
  78851. }
  78852. else {
  78853. points = contours;
  78854. }
  78855. this._addToepoint(points);
  78856. this._points.add(points);
  78857. this._outlinepoints.add(points);
  78858. if (typeof earcut === 'undefined') {
  78859. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  78860. }
  78861. }
  78862. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  78863. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  78864. var p = points_1[_i];
  78865. this._epoints.push(p.x, p.y);
  78866. }
  78867. };
  78868. PolygonMeshBuilder.prototype.addHole = function (hole) {
  78869. this._points.add(hole);
  78870. var holepoints = new PolygonPoints();
  78871. holepoints.add(hole);
  78872. this._holes.push(holepoints);
  78873. this._eholes.push(this._epoints.length / 2);
  78874. this._addToepoint(hole);
  78875. return this;
  78876. };
  78877. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  78878. var _this = this;
  78879. if (updatable === void 0) { updatable = false; }
  78880. if (depth === void 0) { depth = 0; }
  78881. var result = new BABYLON.Mesh(this._name, this._scene);
  78882. var normals = new Array();
  78883. var positions = new Array();
  78884. var uvs = new Array();
  78885. var bounds = this._points.computeBounds();
  78886. this._points.elements.forEach(function (p) {
  78887. normals.push(0, 1.0, 0);
  78888. positions.push(p.x, 0, p.y);
  78889. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  78890. });
  78891. var indices = new Array();
  78892. var res = earcut(this._epoints, this._eholes, 2);
  78893. for (var i = 0; i < res.length; i++) {
  78894. indices.push(res[i]);
  78895. }
  78896. if (depth > 0) {
  78897. var positionscount = (positions.length / 3); //get the current pointcount
  78898. this._points.elements.forEach(function (p) {
  78899. normals.push(0, -1.0, 0);
  78900. positions.push(p.x, -depth, p.y);
  78901. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  78902. });
  78903. var totalCount = indices.length;
  78904. for (var i = 0; i < totalCount; i += 3) {
  78905. var i0 = indices[i + 0];
  78906. var i1 = indices[i + 1];
  78907. var i2 = indices[i + 2];
  78908. indices.push(i2 + positionscount);
  78909. indices.push(i1 + positionscount);
  78910. indices.push(i0 + positionscount);
  78911. }
  78912. //Add the sides
  78913. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  78914. this._holes.forEach(function (hole) {
  78915. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  78916. });
  78917. }
  78918. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  78919. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  78920. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  78921. result.setIndices(indices);
  78922. return result;
  78923. };
  78924. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  78925. var StartIndex = positions.length / 3;
  78926. var ulength = 0;
  78927. for (var i = 0; i < points.elements.length; i++) {
  78928. var p = points.elements[i];
  78929. var p1;
  78930. if ((i + 1) > points.elements.length - 1) {
  78931. p1 = points.elements[0];
  78932. }
  78933. else {
  78934. p1 = points.elements[i + 1];
  78935. }
  78936. positions.push(p.x, 0, p.y);
  78937. positions.push(p.x, -depth, p.y);
  78938. positions.push(p1.x, 0, p1.y);
  78939. positions.push(p1.x, -depth, p1.y);
  78940. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  78941. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  78942. var v3 = v2.subtract(v1);
  78943. var v4 = new BABYLON.Vector3(0, 1, 0);
  78944. var vn = BABYLON.Vector3.Cross(v3, v4);
  78945. vn = vn.normalize();
  78946. uvs.push(ulength / bounds.width, 0);
  78947. uvs.push(ulength / bounds.width, 1);
  78948. ulength += v3.length();
  78949. uvs.push((ulength / bounds.width), 0);
  78950. uvs.push((ulength / bounds.width), 1);
  78951. if (!flip) {
  78952. normals.push(-vn.x, -vn.y, -vn.z);
  78953. normals.push(-vn.x, -vn.y, -vn.z);
  78954. normals.push(-vn.x, -vn.y, -vn.z);
  78955. normals.push(-vn.x, -vn.y, -vn.z);
  78956. indices.push(StartIndex);
  78957. indices.push(StartIndex + 1);
  78958. indices.push(StartIndex + 2);
  78959. indices.push(StartIndex + 1);
  78960. indices.push(StartIndex + 3);
  78961. indices.push(StartIndex + 2);
  78962. }
  78963. else {
  78964. normals.push(vn.x, vn.y, vn.z);
  78965. normals.push(vn.x, vn.y, vn.z);
  78966. normals.push(vn.x, vn.y, vn.z);
  78967. normals.push(vn.x, vn.y, vn.z);
  78968. indices.push(StartIndex);
  78969. indices.push(StartIndex + 2);
  78970. indices.push(StartIndex + 1);
  78971. indices.push(StartIndex + 1);
  78972. indices.push(StartIndex + 2);
  78973. indices.push(StartIndex + 3);
  78974. }
  78975. StartIndex += 4;
  78976. }
  78977. ;
  78978. };
  78979. return PolygonMeshBuilder;
  78980. }());
  78981. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  78982. })(BABYLON || (BABYLON = {}));
  78983. //# sourceMappingURL=babylon.polygonMesh.js.map
  78984. "use strict";
  78985. var BABYLON;
  78986. (function (BABYLON) {
  78987. // Unique ID when we import meshes from Babylon to CSG
  78988. var currentCSGMeshId = 0;
  78989. // # class Vertex
  78990. // Represents a vertex of a polygon. Use your own vertex class instead of this
  78991. // one to provide additional features like texture coordinates and vertex
  78992. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  78993. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  78994. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  78995. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  78996. // is not used anywhere else.
  78997. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  78998. var Vertex = /** @class */ (function () {
  78999. function Vertex(pos, normal, uv) {
  79000. this.pos = pos;
  79001. this.normal = normal;
  79002. this.uv = uv;
  79003. }
  79004. Vertex.prototype.clone = function () {
  79005. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  79006. };
  79007. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  79008. // orientation of a polygon is flipped.
  79009. Vertex.prototype.flip = function () {
  79010. this.normal = this.normal.scale(-1);
  79011. };
  79012. // Create a new vertex between this vertex and `other` by linearly
  79013. // interpolating all properties using a parameter of `t`. Subclasses should
  79014. // override this to interpolate additional properties.
  79015. Vertex.prototype.interpolate = function (other, t) {
  79016. 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));
  79017. };
  79018. return Vertex;
  79019. }());
  79020. // # class Plane
  79021. // Represents a plane in 3D space.
  79022. var Plane = /** @class */ (function () {
  79023. function Plane(normal, w) {
  79024. this.normal = normal;
  79025. this.w = w;
  79026. }
  79027. Plane.FromPoints = function (a, b, c) {
  79028. var v0 = c.subtract(a);
  79029. var v1 = b.subtract(a);
  79030. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  79031. return null;
  79032. }
  79033. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  79034. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  79035. };
  79036. Plane.prototype.clone = function () {
  79037. return new Plane(this.normal.clone(), this.w);
  79038. };
  79039. Plane.prototype.flip = function () {
  79040. this.normal.scaleInPlace(-1);
  79041. this.w = -this.w;
  79042. };
  79043. // Split `polygon` by this plane if needed, then put the polygon or polygon
  79044. // fragments in the appropriate lists. Coplanar polygons go into either
  79045. // `coplanarFront` or `coplanarBack` depending on their orientation with
  79046. // respect to this plane. Polygons in front or in back of this plane go into
  79047. // either `front` or `back`.
  79048. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  79049. var COPLANAR = 0;
  79050. var FRONT = 1;
  79051. var BACK = 2;
  79052. var SPANNING = 3;
  79053. // Classify each point as well as the entire polygon into one of the above
  79054. // four classes.
  79055. var polygonType = 0;
  79056. var types = [];
  79057. var i;
  79058. var t;
  79059. for (i = 0; i < polygon.vertices.length; i++) {
  79060. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  79061. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  79062. polygonType |= type;
  79063. types.push(type);
  79064. }
  79065. // Put the polygon in the correct list, splitting it when necessary.
  79066. switch (polygonType) {
  79067. case COPLANAR:
  79068. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  79069. break;
  79070. case FRONT:
  79071. front.push(polygon);
  79072. break;
  79073. case BACK:
  79074. back.push(polygon);
  79075. break;
  79076. case SPANNING:
  79077. var f = [], b = [];
  79078. for (i = 0; i < polygon.vertices.length; i++) {
  79079. var j = (i + 1) % polygon.vertices.length;
  79080. var ti = types[i], tj = types[j];
  79081. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  79082. if (ti !== BACK)
  79083. f.push(vi);
  79084. if (ti !== FRONT)
  79085. b.push(ti !== BACK ? vi.clone() : vi);
  79086. if ((ti | tj) === SPANNING) {
  79087. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  79088. var v = vi.interpolate(vj, t);
  79089. f.push(v);
  79090. b.push(v.clone());
  79091. }
  79092. }
  79093. var poly;
  79094. if (f.length >= 3) {
  79095. poly = new Polygon(f, polygon.shared);
  79096. if (poly.plane)
  79097. front.push(poly);
  79098. }
  79099. if (b.length >= 3) {
  79100. poly = new Polygon(b, polygon.shared);
  79101. if (poly.plane)
  79102. back.push(poly);
  79103. }
  79104. break;
  79105. }
  79106. };
  79107. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  79108. // point is on the plane.
  79109. Plane.EPSILON = 1e-5;
  79110. return Plane;
  79111. }());
  79112. // # class Polygon
  79113. // Represents a convex polygon. The vertices used to initialize a polygon must
  79114. // be coplanar and form a convex loop.
  79115. //
  79116. // Each convex polygon has a `shared` property, which is shared between all
  79117. // polygons that are clones of each other or were split from the same polygon.
  79118. // This can be used to define per-polygon properties (such as surface color).
  79119. var Polygon = /** @class */ (function () {
  79120. function Polygon(vertices, shared) {
  79121. this.vertices = vertices;
  79122. this.shared = shared;
  79123. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  79124. }
  79125. Polygon.prototype.clone = function () {
  79126. var vertices = this.vertices.map(function (v) { return v.clone(); });
  79127. return new Polygon(vertices, this.shared);
  79128. };
  79129. Polygon.prototype.flip = function () {
  79130. this.vertices.reverse().map(function (v) { v.flip(); });
  79131. this.plane.flip();
  79132. };
  79133. return Polygon;
  79134. }());
  79135. // # class Node
  79136. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  79137. // by picking a polygon to split along. That polygon (and all other coplanar
  79138. // polygons) are added directly to that node and the other polygons are added to
  79139. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  79140. // no distinction between internal and leaf nodes.
  79141. var Node = /** @class */ (function () {
  79142. function Node(polygons) {
  79143. this.plane = null;
  79144. this.front = null;
  79145. this.back = null;
  79146. this.polygons = new Array();
  79147. if (polygons) {
  79148. this.build(polygons);
  79149. }
  79150. }
  79151. Node.prototype.clone = function () {
  79152. var node = new Node();
  79153. node.plane = this.plane && this.plane.clone();
  79154. node.front = this.front && this.front.clone();
  79155. node.back = this.back && this.back.clone();
  79156. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  79157. return node;
  79158. };
  79159. // Convert solid space to empty space and empty space to solid space.
  79160. Node.prototype.invert = function () {
  79161. for (var i = 0; i < this.polygons.length; i++) {
  79162. this.polygons[i].flip();
  79163. }
  79164. if (this.plane) {
  79165. this.plane.flip();
  79166. }
  79167. if (this.front) {
  79168. this.front.invert();
  79169. }
  79170. if (this.back) {
  79171. this.back.invert();
  79172. }
  79173. var temp = this.front;
  79174. this.front = this.back;
  79175. this.back = temp;
  79176. };
  79177. // Recursively remove all polygons in `polygons` that are inside this BSP
  79178. // tree.
  79179. Node.prototype.clipPolygons = function (polygons) {
  79180. if (!this.plane)
  79181. return polygons.slice();
  79182. var front = new Array(), back = new Array();
  79183. for (var i = 0; i < polygons.length; i++) {
  79184. this.plane.splitPolygon(polygons[i], front, back, front, back);
  79185. }
  79186. if (this.front) {
  79187. front = this.front.clipPolygons(front);
  79188. }
  79189. if (this.back) {
  79190. back = this.back.clipPolygons(back);
  79191. }
  79192. else {
  79193. back = [];
  79194. }
  79195. return front.concat(back);
  79196. };
  79197. // Remove all polygons in this BSP tree that are inside the other BSP tree
  79198. // `bsp`.
  79199. Node.prototype.clipTo = function (bsp) {
  79200. this.polygons = bsp.clipPolygons(this.polygons);
  79201. if (this.front)
  79202. this.front.clipTo(bsp);
  79203. if (this.back)
  79204. this.back.clipTo(bsp);
  79205. };
  79206. // Return a list of all polygons in this BSP tree.
  79207. Node.prototype.allPolygons = function () {
  79208. var polygons = this.polygons.slice();
  79209. if (this.front)
  79210. polygons = polygons.concat(this.front.allPolygons());
  79211. if (this.back)
  79212. polygons = polygons.concat(this.back.allPolygons());
  79213. return polygons;
  79214. };
  79215. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  79216. // new polygons are filtered down to the bottom of the tree and become new
  79217. // nodes there. Each set of polygons is partitioned using the first polygon
  79218. // (no heuristic is used to pick a good split).
  79219. Node.prototype.build = function (polygons) {
  79220. if (!polygons.length)
  79221. return;
  79222. if (!this.plane)
  79223. this.plane = polygons[0].plane.clone();
  79224. var front = new Array(), back = new Array();
  79225. for (var i = 0; i < polygons.length; i++) {
  79226. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  79227. }
  79228. if (front.length) {
  79229. if (!this.front)
  79230. this.front = new Node();
  79231. this.front.build(front);
  79232. }
  79233. if (back.length) {
  79234. if (!this.back)
  79235. this.back = new Node();
  79236. this.back.build(back);
  79237. }
  79238. };
  79239. return Node;
  79240. }());
  79241. var CSG = /** @class */ (function () {
  79242. function CSG() {
  79243. this.polygons = new Array();
  79244. }
  79245. // Convert BABYLON.Mesh to BABYLON.CSG
  79246. CSG.FromMesh = function (mesh) {
  79247. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  79248. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  79249. if (mesh instanceof BABYLON.Mesh) {
  79250. mesh.computeWorldMatrix(true);
  79251. matrix = mesh.getWorldMatrix();
  79252. meshPosition = mesh.position.clone();
  79253. meshRotation = mesh.rotation.clone();
  79254. if (mesh.rotationQuaternion) {
  79255. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  79256. }
  79257. meshScaling = mesh.scaling.clone();
  79258. }
  79259. else {
  79260. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  79261. }
  79262. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  79263. var subMeshes = mesh.subMeshes;
  79264. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  79265. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  79266. vertices = [];
  79267. for (var j = 0; j < 3; j++) {
  79268. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  79269. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  79270. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  79271. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  79272. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  79273. vertex = new Vertex(position, normal, uv);
  79274. vertices.push(vertex);
  79275. }
  79276. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  79277. // To handle the case of degenerated triangle
  79278. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  79279. if (polygon.plane)
  79280. polygons.push(polygon);
  79281. }
  79282. }
  79283. var csg = CSG.FromPolygons(polygons);
  79284. csg.matrix = matrix;
  79285. csg.position = meshPosition;
  79286. csg.rotation = meshRotation;
  79287. csg.scaling = meshScaling;
  79288. csg.rotationQuaternion = meshRotationQuaternion;
  79289. currentCSGMeshId++;
  79290. return csg;
  79291. };
  79292. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  79293. CSG.FromPolygons = function (polygons) {
  79294. var csg = new CSG();
  79295. csg.polygons = polygons;
  79296. return csg;
  79297. };
  79298. CSG.prototype.clone = function () {
  79299. var csg = new CSG();
  79300. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  79301. csg.copyTransformAttributes(this);
  79302. return csg;
  79303. };
  79304. CSG.prototype.union = function (csg) {
  79305. var a = new Node(this.clone().polygons);
  79306. var b = new Node(csg.clone().polygons);
  79307. a.clipTo(b);
  79308. b.clipTo(a);
  79309. b.invert();
  79310. b.clipTo(a);
  79311. b.invert();
  79312. a.build(b.allPolygons());
  79313. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79314. };
  79315. CSG.prototype.unionInPlace = function (csg) {
  79316. var a = new Node(this.polygons);
  79317. var b = new Node(csg.polygons);
  79318. a.clipTo(b);
  79319. b.clipTo(a);
  79320. b.invert();
  79321. b.clipTo(a);
  79322. b.invert();
  79323. a.build(b.allPolygons());
  79324. this.polygons = a.allPolygons();
  79325. };
  79326. CSG.prototype.subtract = function (csg) {
  79327. var a = new Node(this.clone().polygons);
  79328. var b = new Node(csg.clone().polygons);
  79329. a.invert();
  79330. a.clipTo(b);
  79331. b.clipTo(a);
  79332. b.invert();
  79333. b.clipTo(a);
  79334. b.invert();
  79335. a.build(b.allPolygons());
  79336. a.invert();
  79337. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79338. };
  79339. CSG.prototype.subtractInPlace = function (csg) {
  79340. var a = new Node(this.polygons);
  79341. var b = new Node(csg.polygons);
  79342. a.invert();
  79343. a.clipTo(b);
  79344. b.clipTo(a);
  79345. b.invert();
  79346. b.clipTo(a);
  79347. b.invert();
  79348. a.build(b.allPolygons());
  79349. a.invert();
  79350. this.polygons = a.allPolygons();
  79351. };
  79352. CSG.prototype.intersect = function (csg) {
  79353. var a = new Node(this.clone().polygons);
  79354. var b = new Node(csg.clone().polygons);
  79355. a.invert();
  79356. b.clipTo(a);
  79357. b.invert();
  79358. a.clipTo(b);
  79359. b.clipTo(a);
  79360. a.build(b.allPolygons());
  79361. a.invert();
  79362. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79363. };
  79364. CSG.prototype.intersectInPlace = function (csg) {
  79365. var a = new Node(this.polygons);
  79366. var b = new Node(csg.polygons);
  79367. a.invert();
  79368. b.clipTo(a);
  79369. b.invert();
  79370. a.clipTo(b);
  79371. b.clipTo(a);
  79372. a.build(b.allPolygons());
  79373. a.invert();
  79374. this.polygons = a.allPolygons();
  79375. };
  79376. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  79377. // not modified.
  79378. CSG.prototype.inverse = function () {
  79379. var csg = this.clone();
  79380. csg.inverseInPlace();
  79381. return csg;
  79382. };
  79383. CSG.prototype.inverseInPlace = function () {
  79384. this.polygons.map(function (p) { p.flip(); });
  79385. };
  79386. // This is used to keep meshes transformations so they can be restored
  79387. // when we build back a Babylon Mesh
  79388. // NB : All CSG operations are performed in world coordinates
  79389. CSG.prototype.copyTransformAttributes = function (csg) {
  79390. this.matrix = csg.matrix;
  79391. this.position = csg.position;
  79392. this.rotation = csg.rotation;
  79393. this.scaling = csg.scaling;
  79394. this.rotationQuaternion = csg.rotationQuaternion;
  79395. return this;
  79396. };
  79397. // Build Raw mesh from CSG
  79398. // Coordinates here are in world space
  79399. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  79400. var matrix = this.matrix.clone();
  79401. matrix.invert();
  79402. 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;
  79403. if (keepSubMeshes) {
  79404. // Sort Polygons, since subMeshes are indices range
  79405. polygons.sort(function (a, b) {
  79406. if (a.shared.meshId === b.shared.meshId) {
  79407. return a.shared.subMeshId - b.shared.subMeshId;
  79408. }
  79409. else {
  79410. return a.shared.meshId - b.shared.meshId;
  79411. }
  79412. });
  79413. }
  79414. for (var i = 0, il = polygons.length; i < il; i++) {
  79415. polygon = polygons[i];
  79416. // Building SubMeshes
  79417. if (!subMesh_dict[polygon.shared.meshId]) {
  79418. subMesh_dict[polygon.shared.meshId] = {};
  79419. }
  79420. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  79421. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  79422. indexStart: +Infinity,
  79423. indexEnd: -Infinity,
  79424. materialIndex: polygon.shared.materialIndex
  79425. };
  79426. }
  79427. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  79428. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  79429. polygonIndices[0] = 0;
  79430. polygonIndices[1] = j - 1;
  79431. polygonIndices[2] = j;
  79432. for (var k = 0; k < 3; k++) {
  79433. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  79434. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  79435. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  79436. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  79437. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  79438. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  79439. // Check if 2 points can be merged
  79440. if (!(typeof vertex_idx !== 'undefined' &&
  79441. normals[vertex_idx * 3] === localNormal.x &&
  79442. normals[vertex_idx * 3 + 1] === localNormal.y &&
  79443. normals[vertex_idx * 3 + 2] === localNormal.z &&
  79444. uvs[vertex_idx * 2] === uv.x &&
  79445. uvs[vertex_idx * 2 + 1] === uv.y)) {
  79446. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  79447. uvs.push(uv.x, uv.y);
  79448. normals.push(normal.x, normal.y, normal.z);
  79449. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  79450. }
  79451. indices.push(vertex_idx);
  79452. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  79453. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  79454. currentIndex++;
  79455. }
  79456. }
  79457. }
  79458. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  79459. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  79460. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  79461. mesh.setIndices(indices, null);
  79462. if (keepSubMeshes) {
  79463. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  79464. var materialIndexOffset = 0, materialMaxIndex;
  79465. mesh.subMeshes = new Array();
  79466. for (var m in subMesh_dict) {
  79467. materialMaxIndex = -1;
  79468. for (var sm in subMesh_dict[m]) {
  79469. subMesh_obj = subMesh_dict[m][sm];
  79470. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  79471. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  79472. }
  79473. materialIndexOffset += ++materialMaxIndex;
  79474. }
  79475. }
  79476. return mesh;
  79477. };
  79478. // Build Mesh from CSG taking material and transforms into account
  79479. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  79480. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  79481. mesh.material = material;
  79482. mesh.position.copyFrom(this.position);
  79483. mesh.rotation.copyFrom(this.rotation);
  79484. if (this.rotationQuaternion) {
  79485. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  79486. }
  79487. mesh.scaling.copyFrom(this.scaling);
  79488. mesh.computeWorldMatrix(true);
  79489. return mesh;
  79490. };
  79491. return CSG;
  79492. }());
  79493. BABYLON.CSG = CSG;
  79494. })(BABYLON || (BABYLON = {}));
  79495. //# sourceMappingURL=babylon.csg.js.map
  79496. "use strict";
  79497. var BABYLON;
  79498. (function (BABYLON) {
  79499. var LensFlare = /** @class */ (function () {
  79500. function LensFlare(size, position, color, imgUrl, system) {
  79501. this.size = size;
  79502. this.position = position;
  79503. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  79504. this.color = color || new BABYLON.Color3(1, 1, 1);
  79505. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  79506. this._system = system;
  79507. system.lensFlares.push(this);
  79508. }
  79509. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  79510. return new LensFlare(size, position, color, imgUrl, system);
  79511. };
  79512. LensFlare.prototype.dispose = function () {
  79513. if (this.texture) {
  79514. this.texture.dispose();
  79515. }
  79516. // Remove from scene
  79517. var index = this._system.lensFlares.indexOf(this);
  79518. this._system.lensFlares.splice(index, 1);
  79519. };
  79520. ;
  79521. return LensFlare;
  79522. }());
  79523. BABYLON.LensFlare = LensFlare;
  79524. })(BABYLON || (BABYLON = {}));
  79525. //# sourceMappingURL=babylon.lensFlare.js.map
  79526. "use strict";
  79527. var BABYLON;
  79528. (function (BABYLON) {
  79529. var LensFlareSystem = /** @class */ (function () {
  79530. function LensFlareSystem(name, emitter, scene) {
  79531. this.name = name;
  79532. this.lensFlares = new Array();
  79533. this.borderLimit = 300;
  79534. this.viewportBorder = 0;
  79535. this.layerMask = 0x0FFFFFFF;
  79536. this._vertexBuffers = {};
  79537. this._isEnabled = true;
  79538. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79539. this._emitter = emitter;
  79540. this.id = name;
  79541. scene.lensFlareSystems.push(this);
  79542. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  79543. var engine = scene.getEngine();
  79544. // VBO
  79545. var vertices = [];
  79546. vertices.push(1, 1);
  79547. vertices.push(-1, 1);
  79548. vertices.push(-1, -1);
  79549. vertices.push(1, -1);
  79550. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79551. // Indices
  79552. var indices = [];
  79553. indices.push(0);
  79554. indices.push(1);
  79555. indices.push(2);
  79556. indices.push(0);
  79557. indices.push(2);
  79558. indices.push(3);
  79559. this._indexBuffer = engine.createIndexBuffer(indices);
  79560. // Effects
  79561. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  79562. }
  79563. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  79564. get: function () {
  79565. return this._isEnabled;
  79566. },
  79567. set: function (value) {
  79568. this._isEnabled = value;
  79569. },
  79570. enumerable: true,
  79571. configurable: true
  79572. });
  79573. LensFlareSystem.prototype.getScene = function () {
  79574. return this._scene;
  79575. };
  79576. LensFlareSystem.prototype.getEmitter = function () {
  79577. return this._emitter;
  79578. };
  79579. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  79580. this._emitter = newEmitter;
  79581. };
  79582. LensFlareSystem.prototype.getEmitterPosition = function () {
  79583. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  79584. };
  79585. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  79586. var position = this.getEmitterPosition();
  79587. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  79588. this._positionX = position.x;
  79589. this._positionY = position.y;
  79590. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  79591. if (this.viewportBorder > 0) {
  79592. globalViewport.x -= this.viewportBorder;
  79593. globalViewport.y -= this.viewportBorder;
  79594. globalViewport.width += this.viewportBorder * 2;
  79595. globalViewport.height += this.viewportBorder * 2;
  79596. position.x += this.viewportBorder;
  79597. position.y += this.viewportBorder;
  79598. this._positionX += this.viewportBorder;
  79599. this._positionY += this.viewportBorder;
  79600. }
  79601. if (position.z > 0) {
  79602. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  79603. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  79604. return true;
  79605. }
  79606. return true;
  79607. }
  79608. return false;
  79609. };
  79610. LensFlareSystem.prototype._isVisible = function () {
  79611. if (!this._isEnabled || !this._scene.activeCamera) {
  79612. return false;
  79613. }
  79614. var emitterPosition = this.getEmitterPosition();
  79615. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  79616. var distance = direction.length();
  79617. direction.normalize();
  79618. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  79619. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  79620. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  79621. };
  79622. LensFlareSystem.prototype.render = function () {
  79623. if (!this._effect.isReady() || !this._scene.activeCamera)
  79624. return false;
  79625. var engine = this._scene.getEngine();
  79626. var viewport = this._scene.activeCamera.viewport;
  79627. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  79628. // Position
  79629. if (!this.computeEffectivePosition(globalViewport)) {
  79630. return false;
  79631. }
  79632. // Visibility
  79633. if (!this._isVisible()) {
  79634. return false;
  79635. }
  79636. // Intensity
  79637. var awayX;
  79638. var awayY;
  79639. if (this._positionX < this.borderLimit + globalViewport.x) {
  79640. awayX = this.borderLimit + globalViewport.x - this._positionX;
  79641. }
  79642. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  79643. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  79644. }
  79645. else {
  79646. awayX = 0;
  79647. }
  79648. if (this._positionY < this.borderLimit + globalViewport.y) {
  79649. awayY = this.borderLimit + globalViewport.y - this._positionY;
  79650. }
  79651. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  79652. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  79653. }
  79654. else {
  79655. awayY = 0;
  79656. }
  79657. var away = (awayX > awayY) ? awayX : awayY;
  79658. away -= this.viewportBorder;
  79659. if (away > this.borderLimit) {
  79660. away = this.borderLimit;
  79661. }
  79662. var intensity = 1.0 - (away / this.borderLimit);
  79663. if (intensity < 0) {
  79664. return false;
  79665. }
  79666. if (intensity > 1.0) {
  79667. intensity = 1.0;
  79668. }
  79669. if (this.viewportBorder > 0) {
  79670. globalViewport.x += this.viewportBorder;
  79671. globalViewport.y += this.viewportBorder;
  79672. globalViewport.width -= this.viewportBorder * 2;
  79673. globalViewport.height -= this.viewportBorder * 2;
  79674. this._positionX -= this.viewportBorder;
  79675. this._positionY -= this.viewportBorder;
  79676. }
  79677. // Position
  79678. var centerX = globalViewport.x + globalViewport.width / 2;
  79679. var centerY = globalViewport.y + globalViewport.height / 2;
  79680. var distX = centerX - this._positionX;
  79681. var distY = centerY - this._positionY;
  79682. // Effects
  79683. engine.enableEffect(this._effect);
  79684. engine.setState(false);
  79685. engine.setDepthBuffer(false);
  79686. // VBOs
  79687. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79688. // Flares
  79689. for (var index = 0; index < this.lensFlares.length; index++) {
  79690. var flare = this.lensFlares[index];
  79691. engine.setAlphaMode(flare.alphaMode);
  79692. var x = centerX - (distX * flare.position);
  79693. var y = centerY - (distY * flare.position);
  79694. var cw = flare.size;
  79695. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  79696. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  79697. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  79698. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  79699. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  79700. // Texture
  79701. this._effect.setTexture("textureSampler", flare.texture);
  79702. // Color
  79703. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  79704. // Draw order
  79705. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79706. }
  79707. engine.setDepthBuffer(true);
  79708. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79709. return true;
  79710. };
  79711. LensFlareSystem.prototype.dispose = function () {
  79712. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79713. if (vertexBuffer) {
  79714. vertexBuffer.dispose();
  79715. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79716. }
  79717. if (this._indexBuffer) {
  79718. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79719. this._indexBuffer = null;
  79720. }
  79721. while (this.lensFlares.length) {
  79722. this.lensFlares[0].dispose();
  79723. }
  79724. // Remove from scene
  79725. var index = this._scene.lensFlareSystems.indexOf(this);
  79726. this._scene.lensFlareSystems.splice(index, 1);
  79727. };
  79728. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  79729. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  79730. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  79731. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  79732. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  79733. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  79734. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  79735. var parsedFlare = parsedLensFlareSystem.flares[index];
  79736. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  79737. }
  79738. return lensFlareSystem;
  79739. };
  79740. LensFlareSystem.prototype.serialize = function () {
  79741. var serializationObject = {};
  79742. serializationObject.id = this.id;
  79743. serializationObject.name = this.name;
  79744. serializationObject.emitterId = this.getEmitter().id;
  79745. serializationObject.borderLimit = this.borderLimit;
  79746. serializationObject.flares = [];
  79747. for (var index = 0; index < this.lensFlares.length; index++) {
  79748. var flare = this.lensFlares[index];
  79749. serializationObject.flares.push({
  79750. size: flare.size,
  79751. position: flare.position,
  79752. color: flare.color.asArray(),
  79753. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  79754. });
  79755. }
  79756. return serializationObject;
  79757. };
  79758. return LensFlareSystem;
  79759. }());
  79760. BABYLON.LensFlareSystem = LensFlareSystem;
  79761. })(BABYLON || (BABYLON = {}));
  79762. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  79763. "use strict";
  79764. var BABYLON;
  79765. (function (BABYLON) {
  79766. /**
  79767. * This is a holder class for the physics joint created by the physics plugin.
  79768. * It holds a set of functions to control the underlying joint.
  79769. */
  79770. var PhysicsJoint = /** @class */ (function () {
  79771. function PhysicsJoint(type, jointData) {
  79772. this.type = type;
  79773. this.jointData = jointData;
  79774. jointData.nativeParams = jointData.nativeParams || {};
  79775. }
  79776. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  79777. get: function () {
  79778. return this._physicsJoint;
  79779. },
  79780. set: function (newJoint) {
  79781. if (this._physicsJoint) {
  79782. //remove from the wolrd
  79783. }
  79784. this._physicsJoint = newJoint;
  79785. },
  79786. enumerable: true,
  79787. configurable: true
  79788. });
  79789. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  79790. set: function (physicsPlugin) {
  79791. this._physicsPlugin = physicsPlugin;
  79792. },
  79793. enumerable: true,
  79794. configurable: true
  79795. });
  79796. /**
  79797. * Execute a function that is physics-plugin specific.
  79798. * @param {Function} func the function that will be executed.
  79799. * It accepts two parameters: the physics world and the physics joint.
  79800. */
  79801. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  79802. func(this._physicsPlugin.world, this._physicsJoint);
  79803. };
  79804. //TODO check if the native joints are the same
  79805. //Joint Types
  79806. PhysicsJoint.DistanceJoint = 0;
  79807. PhysicsJoint.HingeJoint = 1;
  79808. PhysicsJoint.BallAndSocketJoint = 2;
  79809. PhysicsJoint.WheelJoint = 3;
  79810. PhysicsJoint.SliderJoint = 4;
  79811. //OIMO
  79812. PhysicsJoint.PrismaticJoint = 5;
  79813. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  79814. PhysicsJoint.UniversalJoint = 6;
  79815. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  79816. //Cannon
  79817. //Similar to a Ball-Joint. Different in params
  79818. PhysicsJoint.PointToPointJoint = 8;
  79819. //Cannon only at the moment
  79820. PhysicsJoint.SpringJoint = 9;
  79821. PhysicsJoint.LockJoint = 10;
  79822. return PhysicsJoint;
  79823. }());
  79824. BABYLON.PhysicsJoint = PhysicsJoint;
  79825. /**
  79826. * A class representing a physics distance joint.
  79827. */
  79828. var DistanceJoint = /** @class */ (function (_super) {
  79829. __extends(DistanceJoint, _super);
  79830. function DistanceJoint(jointData) {
  79831. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  79832. }
  79833. /**
  79834. * Update the predefined distance.
  79835. */
  79836. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  79837. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  79838. };
  79839. return DistanceJoint;
  79840. }(PhysicsJoint));
  79841. BABYLON.DistanceJoint = DistanceJoint;
  79842. var MotorEnabledJoint = /** @class */ (function (_super) {
  79843. __extends(MotorEnabledJoint, _super);
  79844. function MotorEnabledJoint(type, jointData) {
  79845. return _super.call(this, type, jointData) || this;
  79846. }
  79847. /**
  79848. * Set the motor values.
  79849. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79850. * @param {number} force the force to apply
  79851. * @param {number} maxForce max force for this motor.
  79852. */
  79853. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  79854. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  79855. };
  79856. /**
  79857. * Set the motor's limits.
  79858. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79859. */
  79860. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  79861. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  79862. };
  79863. return MotorEnabledJoint;
  79864. }(PhysicsJoint));
  79865. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  79866. /**
  79867. * This class represents a single hinge physics joint
  79868. */
  79869. var HingeJoint = /** @class */ (function (_super) {
  79870. __extends(HingeJoint, _super);
  79871. function HingeJoint(jointData) {
  79872. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  79873. }
  79874. /**
  79875. * Set the motor values.
  79876. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79877. * @param {number} force the force to apply
  79878. * @param {number} maxForce max force for this motor.
  79879. */
  79880. HingeJoint.prototype.setMotor = function (force, maxForce) {
  79881. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  79882. };
  79883. /**
  79884. * Set the motor's limits.
  79885. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79886. */
  79887. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  79888. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  79889. };
  79890. return HingeJoint;
  79891. }(MotorEnabledJoint));
  79892. BABYLON.HingeJoint = HingeJoint;
  79893. /**
  79894. * This class represents a dual hinge physics joint (same as wheel joint)
  79895. */
  79896. var Hinge2Joint = /** @class */ (function (_super) {
  79897. __extends(Hinge2Joint, _super);
  79898. function Hinge2Joint(jointData) {
  79899. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  79900. }
  79901. /**
  79902. * Set the motor values.
  79903. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79904. * @param {number} force the force to apply
  79905. * @param {number} maxForce max force for this motor.
  79906. * @param {motorIndex} the motor's index, 0 or 1.
  79907. */
  79908. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  79909. if (motorIndex === void 0) { motorIndex = 0; }
  79910. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  79911. };
  79912. /**
  79913. * Set the motor limits.
  79914. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79915. * @param {number} upperLimit the upper limit
  79916. * @param {number} lowerLimit lower limit
  79917. * @param {motorIndex} the motor's index, 0 or 1.
  79918. */
  79919. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  79920. if (motorIndex === void 0) { motorIndex = 0; }
  79921. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  79922. };
  79923. return Hinge2Joint;
  79924. }(MotorEnabledJoint));
  79925. BABYLON.Hinge2Joint = Hinge2Joint;
  79926. })(BABYLON || (BABYLON = {}));
  79927. //# sourceMappingURL=babylon.physicsJoint.js.map
  79928. "use strict";
  79929. var BABYLON;
  79930. (function (BABYLON) {
  79931. var PhysicsImpostor = /** @class */ (function () {
  79932. function PhysicsImpostor(object, type, _options, _scene) {
  79933. if (_options === void 0) { _options = { mass: 0 }; }
  79934. var _this = this;
  79935. this.object = object;
  79936. this.type = type;
  79937. this._options = _options;
  79938. this._scene = _scene;
  79939. this._bodyUpdateRequired = false;
  79940. this._onBeforePhysicsStepCallbacks = new Array();
  79941. this._onAfterPhysicsStepCallbacks = new Array();
  79942. this._onPhysicsCollideCallbacks = [];
  79943. this._deltaPosition = BABYLON.Vector3.Zero();
  79944. this._isDisposed = false;
  79945. //temp variables for parent rotation calculations
  79946. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  79947. this._tmpQuat = new BABYLON.Quaternion();
  79948. this._tmpQuat2 = new BABYLON.Quaternion();
  79949. /**
  79950. * this function is executed by the physics engine.
  79951. */
  79952. this.beforeStep = function () {
  79953. if (!_this._physicsEngine) {
  79954. return;
  79955. }
  79956. _this.object.translate(_this._deltaPosition, -1);
  79957. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  79958. _this.object.computeWorldMatrix(false);
  79959. if (_this.object.parent && _this.object.rotationQuaternion) {
  79960. _this.getParentsRotation();
  79961. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  79962. }
  79963. else {
  79964. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  79965. }
  79966. if (!_this._options.disableBidirectionalTransformation) {
  79967. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  79968. }
  79969. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  79970. func(_this);
  79971. });
  79972. };
  79973. /**
  79974. * this function is executed by the physics engine.
  79975. */
  79976. this.afterStep = function () {
  79977. if (!_this._physicsEngine) {
  79978. return;
  79979. }
  79980. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  79981. func(_this);
  79982. });
  79983. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  79984. // object has now its world rotation. needs to be converted to local.
  79985. if (_this.object.parent && _this.object.rotationQuaternion) {
  79986. _this.getParentsRotation();
  79987. _this._tmpQuat.conjugateInPlace();
  79988. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  79989. }
  79990. // take the position set and make it the absolute position of this object.
  79991. _this.object.setAbsolutePosition(_this.object.position);
  79992. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  79993. _this.object.translate(_this._deltaPosition, 1);
  79994. };
  79995. /**
  79996. * Legacy collision detection event support
  79997. */
  79998. this.onCollideEvent = null;
  79999. //event and body object due to cannon's event-based architecture.
  80000. this.onCollide = function (e) {
  80001. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  80002. return;
  80003. }
  80004. if (!_this._physicsEngine) {
  80005. return;
  80006. }
  80007. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  80008. if (otherImpostor) {
  80009. // Legacy collision detection event support
  80010. if (_this.onCollideEvent) {
  80011. _this.onCollideEvent(_this, otherImpostor);
  80012. }
  80013. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  80014. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  80015. }).forEach(function (obj) {
  80016. obj.callback(_this, otherImpostor);
  80017. });
  80018. }
  80019. };
  80020. //sanity check!
  80021. if (!this.object) {
  80022. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  80023. return;
  80024. }
  80025. //legacy support for old syntax.
  80026. if (!this._scene && object.getScene) {
  80027. this._scene = object.getScene();
  80028. }
  80029. if (!this._scene) {
  80030. return;
  80031. }
  80032. this._physicsEngine = this._scene.getPhysicsEngine();
  80033. if (!this._physicsEngine) {
  80034. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  80035. }
  80036. else {
  80037. //set the object's quaternion, if not set
  80038. if (!this.object.rotationQuaternion) {
  80039. if (this.object.rotation) {
  80040. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  80041. }
  80042. else {
  80043. this.object.rotationQuaternion = new BABYLON.Quaternion();
  80044. }
  80045. }
  80046. //default options params
  80047. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  80048. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  80049. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  80050. this._joints = [];
  80051. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  80052. if (!this.object.parent || this._options.ignoreParent) {
  80053. this._init();
  80054. }
  80055. else if (this.object.parent.physicsImpostor) {
  80056. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  80057. }
  80058. }
  80059. }
  80060. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  80061. get: function () {
  80062. return this._isDisposed;
  80063. },
  80064. enumerable: true,
  80065. configurable: true
  80066. });
  80067. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  80068. get: function () {
  80069. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  80070. },
  80071. set: function (value) {
  80072. this.setMass(value);
  80073. },
  80074. enumerable: true,
  80075. configurable: true
  80076. });
  80077. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  80078. get: function () {
  80079. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  80080. },
  80081. set: function (value) {
  80082. if (!this._physicsEngine) {
  80083. return;
  80084. }
  80085. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  80086. },
  80087. enumerable: true,
  80088. configurable: true
  80089. });
  80090. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  80091. get: function () {
  80092. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  80093. },
  80094. set: function (value) {
  80095. if (!this._physicsEngine) {
  80096. return;
  80097. }
  80098. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  80099. },
  80100. enumerable: true,
  80101. configurable: true
  80102. });
  80103. /**
  80104. * This function will completly initialize this impostor.
  80105. * It will create a new body - but only if this mesh has no parent.
  80106. * If it has, this impostor will not be used other than to define the impostor
  80107. * of the child mesh.
  80108. */
  80109. PhysicsImpostor.prototype._init = function () {
  80110. if (!this._physicsEngine) {
  80111. return;
  80112. }
  80113. this._physicsEngine.removeImpostor(this);
  80114. this.physicsBody = null;
  80115. this._parent = this._parent || this._getPhysicsParent();
  80116. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  80117. this._physicsEngine.addImpostor(this);
  80118. }
  80119. };
  80120. PhysicsImpostor.prototype._getPhysicsParent = function () {
  80121. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  80122. var parentMesh = this.object.parent;
  80123. return parentMesh.physicsImpostor;
  80124. }
  80125. return null;
  80126. };
  80127. /**
  80128. * Should a new body be generated.
  80129. */
  80130. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  80131. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  80132. };
  80133. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  80134. this.forceUpdate();
  80135. };
  80136. /**
  80137. * Force a regeneration of this or the parent's impostor's body.
  80138. * Use under cautious - This will remove all joints already implemented.
  80139. */
  80140. PhysicsImpostor.prototype.forceUpdate = function () {
  80141. this._init();
  80142. if (this.parent && !this._options.ignoreParent) {
  80143. this.parent.forceUpdate();
  80144. }
  80145. };
  80146. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  80147. /*public get mesh(): AbstractMesh {
  80148. return this._mesh;
  80149. }*/
  80150. /**
  80151. * Gets the body that holds this impostor. Either its own, or its parent.
  80152. */
  80153. get: function () {
  80154. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  80155. },
  80156. /**
  80157. * Set the physics body. Used mainly by the physics engine/plugin
  80158. */
  80159. set: function (physicsBody) {
  80160. if (this._physicsBody && this._physicsEngine) {
  80161. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  80162. }
  80163. this._physicsBody = physicsBody;
  80164. this.resetUpdateFlags();
  80165. },
  80166. enumerable: true,
  80167. configurable: true
  80168. });
  80169. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  80170. get: function () {
  80171. return !this._options.ignoreParent && this._parent ? this._parent : null;
  80172. },
  80173. set: function (value) {
  80174. this._parent = value;
  80175. },
  80176. enumerable: true,
  80177. configurable: true
  80178. });
  80179. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  80180. this._bodyUpdateRequired = false;
  80181. };
  80182. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  80183. if (this.object.getBoundingInfo) {
  80184. var q = this.object.rotationQuaternion;
  80185. //reset rotation
  80186. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  80187. //calculate the world matrix with no rotation
  80188. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  80189. var boundingInfo = this.object.getBoundingInfo();
  80190. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  80191. //bring back the rotation
  80192. this.object.rotationQuaternion = q;
  80193. //calculate the world matrix with the new rotation
  80194. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  80195. return size;
  80196. }
  80197. else {
  80198. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  80199. }
  80200. };
  80201. PhysicsImpostor.prototype.getObjectCenter = function () {
  80202. if (this.object.getBoundingInfo) {
  80203. var boundingInfo = this.object.getBoundingInfo();
  80204. return boundingInfo.boundingBox.centerWorld;
  80205. }
  80206. else {
  80207. return this.object.position;
  80208. }
  80209. };
  80210. /**
  80211. * Get a specific parametes from the options parameter.
  80212. */
  80213. PhysicsImpostor.prototype.getParam = function (paramName) {
  80214. return this._options[paramName];
  80215. };
  80216. /**
  80217. * Sets a specific parameter in the options given to the physics plugin
  80218. */
  80219. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  80220. this._options[paramName] = value;
  80221. this._bodyUpdateRequired = true;
  80222. };
  80223. /**
  80224. * Specifically change the body's mass option. Won't recreate the physics body object
  80225. */
  80226. PhysicsImpostor.prototype.setMass = function (mass) {
  80227. if (this.getParam("mass") !== mass) {
  80228. this.setParam("mass", mass);
  80229. }
  80230. if (this._physicsEngine) {
  80231. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  80232. }
  80233. };
  80234. PhysicsImpostor.prototype.getLinearVelocity = function () {
  80235. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  80236. };
  80237. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  80238. if (this._physicsEngine) {
  80239. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  80240. }
  80241. };
  80242. PhysicsImpostor.prototype.getAngularVelocity = function () {
  80243. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  80244. };
  80245. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  80246. if (this._physicsEngine) {
  80247. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  80248. }
  80249. };
  80250. /**
  80251. * Execute a function with the physics plugin native code.
  80252. * Provide a function the will have two variables - the world object and the physics body object.
  80253. */
  80254. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  80255. if (this._physicsEngine) {
  80256. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  80257. }
  80258. };
  80259. /**
  80260. * Register a function that will be executed before the physics world is stepping forward.
  80261. */
  80262. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  80263. this._onBeforePhysicsStepCallbacks.push(func);
  80264. };
  80265. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  80266. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  80267. if (index > -1) {
  80268. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  80269. }
  80270. else {
  80271. BABYLON.Tools.Warn("Function to remove was not found");
  80272. }
  80273. };
  80274. /**
  80275. * Register a function that will be executed after the physics step
  80276. */
  80277. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  80278. this._onAfterPhysicsStepCallbacks.push(func);
  80279. };
  80280. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  80281. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  80282. if (index > -1) {
  80283. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  80284. }
  80285. else {
  80286. BABYLON.Tools.Warn("Function to remove was not found");
  80287. }
  80288. };
  80289. /**
  80290. * register a function that will be executed when this impostor collides against a different body.
  80291. */
  80292. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  80293. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  80294. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  80295. };
  80296. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  80297. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  80298. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  80299. if (index > -1) {
  80300. this._onPhysicsCollideCallbacks.splice(index, 1);
  80301. }
  80302. else {
  80303. BABYLON.Tools.Warn("Function to remove was not found");
  80304. }
  80305. };
  80306. PhysicsImpostor.prototype.getParentsRotation = function () {
  80307. var parent = this.object.parent;
  80308. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  80309. while (parent) {
  80310. if (parent.rotationQuaternion) {
  80311. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  80312. }
  80313. else {
  80314. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  80315. }
  80316. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  80317. parent = parent.parent;
  80318. }
  80319. return this._tmpQuat;
  80320. };
  80321. /**
  80322. * Apply a force
  80323. */
  80324. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  80325. if (this._physicsEngine) {
  80326. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  80327. }
  80328. return this;
  80329. };
  80330. /**
  80331. * Apply an impulse
  80332. */
  80333. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  80334. if (this._physicsEngine) {
  80335. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  80336. }
  80337. return this;
  80338. };
  80339. /**
  80340. * A help function to create a joint.
  80341. */
  80342. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  80343. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  80344. this.addJoint(otherImpostor, joint);
  80345. return this;
  80346. };
  80347. /**
  80348. * Add a joint to this impostor with a different impostor.
  80349. */
  80350. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  80351. this._joints.push({
  80352. otherImpostor: otherImpostor,
  80353. joint: joint
  80354. });
  80355. if (this._physicsEngine) {
  80356. this._physicsEngine.addJoint(this, otherImpostor, joint);
  80357. }
  80358. return this;
  80359. };
  80360. /**
  80361. * Will keep this body still, in a sleep mode.
  80362. */
  80363. PhysicsImpostor.prototype.sleep = function () {
  80364. if (this._physicsEngine) {
  80365. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  80366. }
  80367. return this;
  80368. };
  80369. /**
  80370. * Wake the body up.
  80371. */
  80372. PhysicsImpostor.prototype.wakeUp = function () {
  80373. if (this._physicsEngine) {
  80374. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  80375. }
  80376. return this;
  80377. };
  80378. PhysicsImpostor.prototype.clone = function (newObject) {
  80379. if (!newObject)
  80380. return null;
  80381. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  80382. };
  80383. PhysicsImpostor.prototype.dispose = function () {
  80384. var _this = this;
  80385. //no dispose if no physics engine is available.
  80386. if (!this._physicsEngine) {
  80387. return;
  80388. }
  80389. this._joints.forEach(function (j) {
  80390. if (_this._physicsEngine) {
  80391. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  80392. }
  80393. });
  80394. //dispose the physics body
  80395. this._physicsEngine.removeImpostor(this);
  80396. if (this.parent) {
  80397. this.parent.forceUpdate();
  80398. }
  80399. else {
  80400. /*this._object.getChildMeshes().forEach(function(mesh) {
  80401. if (mesh.physicsImpostor) {
  80402. if (disposeChildren) {
  80403. mesh.physicsImpostor.dispose();
  80404. mesh.physicsImpostor = null;
  80405. }
  80406. }
  80407. })*/
  80408. }
  80409. this._isDisposed = true;
  80410. };
  80411. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  80412. this._deltaPosition.copyFrom(position);
  80413. };
  80414. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  80415. if (!this._deltaRotation) {
  80416. this._deltaRotation = new BABYLON.Quaternion();
  80417. }
  80418. this._deltaRotation.copyFrom(rotation);
  80419. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  80420. };
  80421. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  80422. if (this._physicsEngine) {
  80423. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  80424. }
  80425. return this;
  80426. };
  80427. PhysicsImpostor.prototype.getRadius = function () {
  80428. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  80429. };
  80430. /**
  80431. * Sync a bone with this impostor
  80432. * @param bone The bone to sync to the impostor.
  80433. * @param boneMesh The mesh that the bone is influencing.
  80434. * @param jointPivot The pivot of the joint / bone in local space.
  80435. * @param distToJoint Optional distance from the impostor to the joint.
  80436. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  80437. */
  80438. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  80439. var tempVec = PhysicsImpostor._tmpVecs[0];
  80440. var mesh = this.object;
  80441. if (mesh.rotationQuaternion) {
  80442. if (adjustRotation) {
  80443. var tempQuat = PhysicsImpostor._tmpQuat;
  80444. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  80445. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  80446. }
  80447. else {
  80448. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  80449. }
  80450. }
  80451. tempVec.x = 0;
  80452. tempVec.y = 0;
  80453. tempVec.z = 0;
  80454. if (jointPivot) {
  80455. tempVec.x = jointPivot.x;
  80456. tempVec.y = jointPivot.y;
  80457. tempVec.z = jointPivot.z;
  80458. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  80459. if (distToJoint === undefined || distToJoint === null) {
  80460. distToJoint = jointPivot.length();
  80461. }
  80462. tempVec.x *= distToJoint;
  80463. tempVec.y *= distToJoint;
  80464. tempVec.z *= distToJoint;
  80465. }
  80466. if (bone.getParent()) {
  80467. tempVec.addInPlace(mesh.getAbsolutePosition());
  80468. bone.setAbsolutePosition(tempVec, boneMesh);
  80469. }
  80470. else {
  80471. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  80472. boneMesh.position.x -= tempVec.x;
  80473. boneMesh.position.y -= tempVec.y;
  80474. boneMesh.position.z -= tempVec.z;
  80475. }
  80476. };
  80477. /**
  80478. * Sync impostor to a bone
  80479. * @param bone The bone that the impostor will be synced to.
  80480. * @param boneMesh The mesh that the bone is influencing.
  80481. * @param jointPivot The pivot of the joint / bone in local space.
  80482. * @param distToJoint Optional distance from the impostor to the joint.
  80483. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  80484. * @param boneAxis Optional vector3 axis the bone is aligned with
  80485. */
  80486. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  80487. var mesh = this.object;
  80488. if (mesh.rotationQuaternion) {
  80489. if (adjustRotation) {
  80490. var tempQuat = PhysicsImpostor._tmpQuat;
  80491. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  80492. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  80493. }
  80494. else {
  80495. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  80496. }
  80497. }
  80498. var pos = PhysicsImpostor._tmpVecs[0];
  80499. var boneDir = PhysicsImpostor._tmpVecs[1];
  80500. if (!boneAxis) {
  80501. boneAxis = PhysicsImpostor._tmpVecs[2];
  80502. boneAxis.x = 0;
  80503. boneAxis.y = 1;
  80504. boneAxis.z = 0;
  80505. }
  80506. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  80507. bone.getAbsolutePositionToRef(boneMesh, pos);
  80508. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  80509. distToJoint = jointPivot.length();
  80510. }
  80511. if (distToJoint !== undefined && distToJoint !== null) {
  80512. pos.x += boneDir.x * distToJoint;
  80513. pos.y += boneDir.y * distToJoint;
  80514. pos.z += boneDir.z * distToJoint;
  80515. }
  80516. mesh.setAbsolutePosition(pos);
  80517. };
  80518. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  80519. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  80520. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80521. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  80522. //Impostor types
  80523. PhysicsImpostor.NoImpostor = 0;
  80524. PhysicsImpostor.SphereImpostor = 1;
  80525. PhysicsImpostor.BoxImpostor = 2;
  80526. PhysicsImpostor.PlaneImpostor = 3;
  80527. PhysicsImpostor.MeshImpostor = 4;
  80528. PhysicsImpostor.CylinderImpostor = 7;
  80529. PhysicsImpostor.ParticleImpostor = 8;
  80530. PhysicsImpostor.HeightmapImpostor = 9;
  80531. return PhysicsImpostor;
  80532. }());
  80533. BABYLON.PhysicsImpostor = PhysicsImpostor;
  80534. })(BABYLON || (BABYLON = {}));
  80535. //# sourceMappingURL=babylon.physicsImpostor.js.map
  80536. "use strict";
  80537. var BABYLON;
  80538. (function (BABYLON) {
  80539. var PhysicsEngine = /** @class */ (function () {
  80540. function PhysicsEngine(gravity, _physicsPlugin) {
  80541. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  80542. this._physicsPlugin = _physicsPlugin;
  80543. //new methods and parameters
  80544. this._impostors = [];
  80545. this._joints = [];
  80546. if (!this._physicsPlugin.isSupported()) {
  80547. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  80548. + "Please make sure it is included.");
  80549. }
  80550. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  80551. this.setGravity(gravity);
  80552. this.setTimeStep();
  80553. }
  80554. PhysicsEngine.prototype.setGravity = function (gravity) {
  80555. this.gravity = gravity;
  80556. this._physicsPlugin.setGravity(this.gravity);
  80557. };
  80558. /**
  80559. * Set the time step of the physics engine.
  80560. * default is 1/60.
  80561. * To slow it down, enter 1/600 for example.
  80562. * To speed it up, 1/30
  80563. * @param {number} newTimeStep the new timestep to apply to this world.
  80564. */
  80565. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  80566. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  80567. this._physicsPlugin.setTimeStep(newTimeStep);
  80568. };
  80569. /**
  80570. * Get the time step of the physics engine.
  80571. */
  80572. PhysicsEngine.prototype.getTimeStep = function () {
  80573. return this._physicsPlugin.getTimeStep();
  80574. };
  80575. PhysicsEngine.prototype.dispose = function () {
  80576. this._impostors.forEach(function (impostor) {
  80577. impostor.dispose();
  80578. });
  80579. this._physicsPlugin.dispose();
  80580. };
  80581. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  80582. return this._physicsPlugin.name;
  80583. };
  80584. /**
  80585. * Adding a new impostor for the impostor tracking.
  80586. * This will be done by the impostor itself.
  80587. * @param {PhysicsImpostor} impostor the impostor to add
  80588. */
  80589. PhysicsEngine.prototype.addImpostor = function (impostor) {
  80590. impostor.uniqueId = this._impostors.push(impostor);
  80591. //if no parent, generate the body
  80592. if (!impostor.parent) {
  80593. this._physicsPlugin.generatePhysicsBody(impostor);
  80594. }
  80595. };
  80596. /**
  80597. * Remove an impostor from the engine.
  80598. * This impostor and its mesh will not longer be updated by the physics engine.
  80599. * @param {PhysicsImpostor} impostor the impostor to remove
  80600. */
  80601. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  80602. var index = this._impostors.indexOf(impostor);
  80603. if (index > -1) {
  80604. var removed = this._impostors.splice(index, 1);
  80605. //Is it needed?
  80606. if (removed.length) {
  80607. //this will also remove it from the world.
  80608. removed[0].physicsBody = null;
  80609. }
  80610. }
  80611. };
  80612. /**
  80613. * Add a joint to the physics engine
  80614. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  80615. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  80616. * @param {PhysicsJoint} the joint that will connect both impostors.
  80617. */
  80618. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  80619. var impostorJoint = {
  80620. mainImpostor: mainImpostor,
  80621. connectedImpostor: connectedImpostor,
  80622. joint: joint
  80623. };
  80624. joint.physicsPlugin = this._physicsPlugin;
  80625. this._joints.push(impostorJoint);
  80626. this._physicsPlugin.generateJoint(impostorJoint);
  80627. };
  80628. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  80629. var matchingJoints = this._joints.filter(function (impostorJoint) {
  80630. return (impostorJoint.connectedImpostor === connectedImpostor
  80631. && impostorJoint.joint === joint
  80632. && impostorJoint.mainImpostor === mainImpostor);
  80633. });
  80634. if (matchingJoints.length) {
  80635. this._physicsPlugin.removeJoint(matchingJoints[0]);
  80636. //TODO remove it from the list as well
  80637. }
  80638. };
  80639. /**
  80640. * Called by the scene. no need to call it.
  80641. */
  80642. PhysicsEngine.prototype._step = function (delta) {
  80643. var _this = this;
  80644. //check if any mesh has no body / requires an update
  80645. this._impostors.forEach(function (impostor) {
  80646. if (impostor.isBodyInitRequired()) {
  80647. _this._physicsPlugin.generatePhysicsBody(impostor);
  80648. }
  80649. });
  80650. if (delta > 0.1) {
  80651. delta = 0.1;
  80652. }
  80653. else if (delta <= 0) {
  80654. delta = 1.0 / 60.0;
  80655. }
  80656. this._physicsPlugin.executeStep(delta, this._impostors);
  80657. };
  80658. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  80659. return this._physicsPlugin;
  80660. };
  80661. PhysicsEngine.prototype.getImpostors = function () {
  80662. return this._impostors;
  80663. };
  80664. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  80665. for (var i = 0; i < this._impostors.length; ++i) {
  80666. if (this._impostors[i].object === object) {
  80667. return this._impostors[i];
  80668. }
  80669. }
  80670. return null;
  80671. };
  80672. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  80673. for (var i = 0; i < this._impostors.length; ++i) {
  80674. if (this._impostors[i].physicsBody === body) {
  80675. return this._impostors[i];
  80676. }
  80677. }
  80678. return null;
  80679. };
  80680. // Statics
  80681. PhysicsEngine.Epsilon = 0.001;
  80682. return PhysicsEngine;
  80683. }());
  80684. BABYLON.PhysicsEngine = PhysicsEngine;
  80685. })(BABYLON || (BABYLON = {}));
  80686. //# sourceMappingURL=babylon.physicsEngine.js.map
  80687. "use strict";
  80688. var BABYLON;
  80689. (function (BABYLON) {
  80690. var PhysicsHelper = /** @class */ (function () {
  80691. function PhysicsHelper(scene) {
  80692. this._scene = scene;
  80693. this._physicsEngine = this._scene.getPhysicsEngine();
  80694. if (!this._physicsEngine) {
  80695. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  80696. }
  80697. }
  80698. /**
  80699. * @param {Vector3} origin the origin of the explosion
  80700. * @param {number} radius the explosion radius
  80701. * @param {number} strength the explosion strength
  80702. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80703. */
  80704. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  80705. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80706. if (!this._physicsEngine) {
  80707. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  80708. return null;
  80709. }
  80710. var impostors = this._physicsEngine.getImpostors();
  80711. if (impostors.length === 0) {
  80712. return null;
  80713. }
  80714. var event = new PhysicsRadialExplosionEvent(this._scene);
  80715. impostors.forEach(function (impostor) {
  80716. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  80717. if (!impostorForceAndContactPoint) {
  80718. return;
  80719. }
  80720. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80721. });
  80722. event.dispose(false);
  80723. return event;
  80724. };
  80725. /**
  80726. * @param {Vector3} origin the origin of the explosion
  80727. * @param {number} radius the explosion radius
  80728. * @param {number} strength the explosion strength
  80729. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80730. */
  80731. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  80732. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80733. if (!this._physicsEngine) {
  80734. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80735. return null;
  80736. }
  80737. var impostors = this._physicsEngine.getImpostors();
  80738. if (impostors.length === 0) {
  80739. return null;
  80740. }
  80741. var event = new PhysicsRadialExplosionEvent(this._scene);
  80742. impostors.forEach(function (impostor) {
  80743. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  80744. if (!impostorForceAndContactPoint) {
  80745. return;
  80746. }
  80747. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80748. });
  80749. event.dispose(false);
  80750. return event;
  80751. };
  80752. /**
  80753. * @param {Vector3} origin the origin of the explosion
  80754. * @param {number} radius the explosion radius
  80755. * @param {number} strength the explosion strength
  80756. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80757. */
  80758. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  80759. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80760. if (!this._physicsEngine) {
  80761. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80762. return null;
  80763. }
  80764. var impostors = this._physicsEngine.getImpostors();
  80765. if (impostors.length === 0) {
  80766. return null;
  80767. }
  80768. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  80769. event.dispose(false);
  80770. return event;
  80771. };
  80772. /**
  80773. * @param {Vector3} origin the origin of the updraft
  80774. * @param {number} radius the radius of the updraft
  80775. * @param {number} strength the strength of the updraft
  80776. * @param {number} height the height of the updraft
  80777. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  80778. */
  80779. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  80780. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  80781. if (!this._physicsEngine) {
  80782. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80783. return null;
  80784. }
  80785. if (this._physicsEngine.getImpostors().length === 0) {
  80786. return null;
  80787. }
  80788. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  80789. event.dispose(false);
  80790. return event;
  80791. };
  80792. /**
  80793. * @param {Vector3} origin the of the vortex
  80794. * @param {number} radius the radius of the vortex
  80795. * @param {number} strength the strength of the vortex
  80796. * @param {number} height the height of the vortex
  80797. */
  80798. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  80799. if (!this._physicsEngine) {
  80800. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80801. return null;
  80802. }
  80803. if (this._physicsEngine.getImpostors().length === 0) {
  80804. return null;
  80805. }
  80806. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  80807. event.dispose(false);
  80808. return event;
  80809. };
  80810. return PhysicsHelper;
  80811. }());
  80812. BABYLON.PhysicsHelper = PhysicsHelper;
  80813. /***** Radial explosion *****/
  80814. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  80815. function PhysicsRadialExplosionEvent(scene) {
  80816. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  80817. this._rays = [];
  80818. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  80819. this._scene = scene;
  80820. }
  80821. /**
  80822. * Returns the data related to the radial explosion event (sphere & rays).
  80823. * @returns {PhysicsRadialExplosionEventData}
  80824. */
  80825. PhysicsRadialExplosionEvent.prototype.getData = function () {
  80826. this._dataFetched = true;
  80827. return {
  80828. sphere: this._sphere,
  80829. rays: this._rays,
  80830. };
  80831. };
  80832. /**
  80833. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  80834. * @param impostor
  80835. * @param {Vector3} origin the origin of the explosion
  80836. * @param {number} radius the explosion radius
  80837. * @param {number} strength the explosion strength
  80838. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  80839. * @returns {Nullable<PhysicsForceAndContactPoint>}
  80840. */
  80841. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  80842. if (impostor.mass === 0) {
  80843. return null;
  80844. }
  80845. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  80846. return null;
  80847. }
  80848. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  80849. return null;
  80850. }
  80851. var impostorObjectCenter = impostor.getObjectCenter();
  80852. var direction = impostorObjectCenter.subtract(origin);
  80853. var ray = new BABYLON.Ray(origin, direction, radius);
  80854. this._rays.push(ray);
  80855. var hit = ray.intersectsMesh(impostor.object);
  80856. var contactPoint = hit.pickedPoint;
  80857. if (!contactPoint) {
  80858. return null;
  80859. }
  80860. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  80861. if (distanceFromOrigin > radius) {
  80862. return null;
  80863. }
  80864. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  80865. ? strength
  80866. : strength * (1 - (distanceFromOrigin / radius));
  80867. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  80868. return { force: force, contactPoint: contactPoint };
  80869. };
  80870. /**
  80871. * Disposes the sphere.
  80872. * @param {bolean} force
  80873. */
  80874. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  80875. var _this = this;
  80876. if (force === void 0) { force = true; }
  80877. if (force) {
  80878. this._sphere.dispose();
  80879. }
  80880. else {
  80881. setTimeout(function () {
  80882. if (!_this._dataFetched) {
  80883. _this._sphere.dispose();
  80884. }
  80885. }, 0);
  80886. }
  80887. };
  80888. /*** Helpers ***/
  80889. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  80890. if (!this._sphere) {
  80891. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  80892. this._sphere.isVisible = false;
  80893. }
  80894. };
  80895. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  80896. var impostorObject = impostor.object;
  80897. this._prepareSphere();
  80898. this._sphere.position = origin;
  80899. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  80900. this._sphere._updateBoundingInfo();
  80901. this._sphere.computeWorldMatrix(true);
  80902. return this._sphere.intersectsMesh(impostorObject, true);
  80903. };
  80904. return PhysicsRadialExplosionEvent;
  80905. }());
  80906. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  80907. /***** Gravitational Field *****/
  80908. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  80909. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  80910. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80911. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80912. this._physicsHelper = physicsHelper;
  80913. this._scene = scene;
  80914. this._origin = origin;
  80915. this._radius = radius;
  80916. this._strength = strength;
  80917. this._falloff = falloff;
  80918. this._tickCallback = this._tick.bind(this);
  80919. }
  80920. /**
  80921. * Returns the data related to the gravitational field event (sphere).
  80922. * @returns {PhysicsGravitationalFieldEventData}
  80923. */
  80924. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  80925. this._dataFetched = true;
  80926. return {
  80927. sphere: this._sphere,
  80928. };
  80929. };
  80930. /**
  80931. * Enables the gravitational field.
  80932. */
  80933. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  80934. this._tickCallback.call(this);
  80935. this._scene.registerBeforeRender(this._tickCallback);
  80936. };
  80937. /**
  80938. * Disables the gravitational field.
  80939. */
  80940. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  80941. this._scene.unregisterBeforeRender(this._tickCallback);
  80942. };
  80943. /**
  80944. * Disposes the sphere.
  80945. * @param {bolean} force
  80946. */
  80947. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  80948. var _this = this;
  80949. if (force === void 0) { force = true; }
  80950. if (force) {
  80951. this._sphere.dispose();
  80952. }
  80953. else {
  80954. setTimeout(function () {
  80955. if (!_this._dataFetched) {
  80956. _this._sphere.dispose();
  80957. }
  80958. }, 0);
  80959. }
  80960. };
  80961. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  80962. // Since the params won't change, we fetch the event only once
  80963. if (this._sphere) {
  80964. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  80965. }
  80966. else {
  80967. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  80968. if (radialExplosionEvent) {
  80969. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  80970. }
  80971. }
  80972. };
  80973. return PhysicsGravitationalFieldEvent;
  80974. }());
  80975. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  80976. /***** Updraft *****/
  80977. var PhysicsUpdraftEvent = /** @class */ (function () {
  80978. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  80979. this._scene = _scene;
  80980. this._origin = _origin;
  80981. this._radius = _radius;
  80982. this._strength = _strength;
  80983. this._height = _height;
  80984. this._updraftMode = _updraftMode;
  80985. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  80986. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  80987. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  80988. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80989. this._physicsEngine = this._scene.getPhysicsEngine();
  80990. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  80991. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  80992. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  80993. this._originDirection = this._origin.subtract(this._originTop).normalize();
  80994. }
  80995. this._tickCallback = this._tick.bind(this);
  80996. }
  80997. /**
  80998. * Returns the data related to the updraft event (cylinder).
  80999. * @returns {PhysicsUpdraftEventData}
  81000. */
  81001. PhysicsUpdraftEvent.prototype.getData = function () {
  81002. this._dataFetched = true;
  81003. return {
  81004. cylinder: this._cylinder,
  81005. };
  81006. };
  81007. /**
  81008. * Enables the updraft.
  81009. */
  81010. PhysicsUpdraftEvent.prototype.enable = function () {
  81011. this._tickCallback.call(this);
  81012. this._scene.registerBeforeRender(this._tickCallback);
  81013. };
  81014. /**
  81015. * Disables the cortex.
  81016. */
  81017. PhysicsUpdraftEvent.prototype.disable = function () {
  81018. this._scene.unregisterBeforeRender(this._tickCallback);
  81019. };
  81020. /**
  81021. * Disposes the sphere.
  81022. * @param {bolean} force
  81023. */
  81024. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  81025. var _this = this;
  81026. if (force === void 0) { force = true; }
  81027. if (force) {
  81028. this._cylinder.dispose();
  81029. }
  81030. else {
  81031. setTimeout(function () {
  81032. if (!_this._dataFetched) {
  81033. _this._cylinder.dispose();
  81034. }
  81035. }, 0);
  81036. }
  81037. };
  81038. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  81039. if (impostor.mass === 0) {
  81040. return null;
  81041. }
  81042. if (!this._intersectsWithCylinder(impostor)) {
  81043. return null;
  81044. }
  81045. var impostorObjectCenter = impostor.getObjectCenter();
  81046. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  81047. var direction = this._originDirection;
  81048. }
  81049. else {
  81050. var direction = impostorObjectCenter.subtract(this._originTop);
  81051. }
  81052. var multiplier = this._strength * -1;
  81053. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  81054. return { force: force, contactPoint: impostorObjectCenter };
  81055. };
  81056. PhysicsUpdraftEvent.prototype._tick = function () {
  81057. var _this = this;
  81058. this._physicsEngine.getImpostors().forEach(function (impostor) {
  81059. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  81060. if (!impostorForceAndContactPoint) {
  81061. return;
  81062. }
  81063. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81064. });
  81065. };
  81066. /*** Helpers ***/
  81067. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  81068. if (!this._cylinder) {
  81069. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  81070. height: this._height,
  81071. diameter: this._radius * 2,
  81072. }, this._scene);
  81073. this._cylinder.isVisible = false;
  81074. }
  81075. };
  81076. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  81077. var impostorObject = impostor.object;
  81078. this._prepareCylinder();
  81079. this._cylinder.position = this._cylinderPosition;
  81080. return this._cylinder.intersectsMesh(impostorObject, true);
  81081. };
  81082. return PhysicsUpdraftEvent;
  81083. }());
  81084. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  81085. /***** Vortex *****/
  81086. var PhysicsVortexEvent = /** @class */ (function () {
  81087. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  81088. this._scene = _scene;
  81089. this._origin = _origin;
  81090. this._radius = _radius;
  81091. this._strength = _strength;
  81092. this._height = _height;
  81093. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  81094. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  81095. this._updraftMultiplier = 0.02;
  81096. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  81097. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81098. this._physicsEngine = this._scene.getPhysicsEngine();
  81099. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  81100. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  81101. this._tickCallback = this._tick.bind(this);
  81102. }
  81103. /**
  81104. * Returns the data related to the vortex event (cylinder).
  81105. * @returns {PhysicsVortexEventData}
  81106. */
  81107. PhysicsVortexEvent.prototype.getData = function () {
  81108. this._dataFetched = true;
  81109. return {
  81110. cylinder: this._cylinder,
  81111. };
  81112. };
  81113. /**
  81114. * Enables the vortex.
  81115. */
  81116. PhysicsVortexEvent.prototype.enable = function () {
  81117. this._tickCallback.call(this);
  81118. this._scene.registerBeforeRender(this._tickCallback);
  81119. };
  81120. /**
  81121. * Disables the cortex.
  81122. */
  81123. PhysicsVortexEvent.prototype.disable = function () {
  81124. this._scene.unregisterBeforeRender(this._tickCallback);
  81125. };
  81126. /**
  81127. * Disposes the sphere.
  81128. * @param {bolean} force
  81129. */
  81130. PhysicsVortexEvent.prototype.dispose = function (force) {
  81131. var _this = this;
  81132. if (force === void 0) { force = true; }
  81133. if (force) {
  81134. this._cylinder.dispose();
  81135. }
  81136. else {
  81137. setTimeout(function () {
  81138. if (!_this._dataFetched) {
  81139. _this._cylinder.dispose();
  81140. }
  81141. }, 0);
  81142. }
  81143. };
  81144. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  81145. if (impostor.mass === 0) {
  81146. return null;
  81147. }
  81148. if (!this._intersectsWithCylinder(impostor)) {
  81149. return null;
  81150. }
  81151. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  81152. return null;
  81153. }
  81154. var impostorObjectCenter = impostor.getObjectCenter();
  81155. 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)
  81156. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  81157. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  81158. var hit = ray.intersectsMesh(impostor.object);
  81159. var contactPoint = hit.pickedPoint;
  81160. if (!contactPoint) {
  81161. return null;
  81162. }
  81163. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  81164. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  81165. var directionToOrigin = contactPoint.normalize();
  81166. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  81167. directionToOrigin = directionToOrigin.negate();
  81168. }
  81169. // TODO: find a more physically based solution
  81170. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  81171. var forceX = directionToOrigin.x * this._strength / 8;
  81172. var forceY = directionToOrigin.y * this._updraftMultiplier;
  81173. var forceZ = directionToOrigin.z * this._strength / 8;
  81174. }
  81175. else {
  81176. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  81177. var forceY = this._originTop.y * this._updraftMultiplier;
  81178. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  81179. }
  81180. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  81181. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  81182. return { force: force, contactPoint: impostorObjectCenter };
  81183. };
  81184. PhysicsVortexEvent.prototype._tick = function () {
  81185. var _this = this;
  81186. this._physicsEngine.getImpostors().forEach(function (impostor) {
  81187. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  81188. if (!impostorForceAndContactPoint) {
  81189. return;
  81190. }
  81191. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81192. });
  81193. };
  81194. /*** Helpers ***/
  81195. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  81196. if (!this._cylinder) {
  81197. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  81198. height: this._height,
  81199. diameter: this._radius * 2,
  81200. }, this._scene);
  81201. this._cylinder.isVisible = false;
  81202. }
  81203. };
  81204. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  81205. var impostorObject = impostor.object;
  81206. this._prepareCylinder();
  81207. this._cylinder.position = this._cylinderPosition;
  81208. return this._cylinder.intersectsMesh(impostorObject, true);
  81209. };
  81210. return PhysicsVortexEvent;
  81211. }());
  81212. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  81213. /***** Enums *****/
  81214. /**
  81215. * The strenght of the force in correspondence to the distance of the affected object
  81216. */
  81217. var PhysicsRadialImpulseFalloff;
  81218. (function (PhysicsRadialImpulseFalloff) {
  81219. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  81220. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  81221. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  81222. /**
  81223. * The strenght of the force in correspondence to the distance of the affected object
  81224. */
  81225. var PhysicsUpdraftMode;
  81226. (function (PhysicsUpdraftMode) {
  81227. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  81228. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  81229. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  81230. })(BABYLON || (BABYLON = {}));
  81231. //# sourceMappingURL=babylon.physicsHelper.js.map
  81232. "use strict";
  81233. var BABYLON;
  81234. (function (BABYLON) {
  81235. var CannonJSPlugin = /** @class */ (function () {
  81236. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  81237. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  81238. if (iterations === void 0) { iterations = 10; }
  81239. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  81240. this.name = "CannonJSPlugin";
  81241. this._physicsMaterials = new Array();
  81242. this._fixedTimeStep = 1 / 60;
  81243. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  81244. this.BJSCANNON = CANNON;
  81245. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  81246. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  81247. this._tmpPosition = BABYLON.Vector3.Zero();
  81248. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  81249. this._tmpUnityRotation = new BABYLON.Quaternion();
  81250. if (!this.isSupported()) {
  81251. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  81252. return;
  81253. }
  81254. this._extendNamespace();
  81255. this.world = new this.BJSCANNON.World();
  81256. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  81257. this.world.solver.iterations = iterations;
  81258. }
  81259. CannonJSPlugin.prototype.setGravity = function (gravity) {
  81260. this.world.gravity.copy(gravity);
  81261. };
  81262. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  81263. this._fixedTimeStep = timeStep;
  81264. };
  81265. CannonJSPlugin.prototype.getTimeStep = function () {
  81266. return this._fixedTimeStep;
  81267. };
  81268. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  81269. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  81270. };
  81271. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  81272. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  81273. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  81274. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  81275. };
  81276. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  81277. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  81278. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  81279. impostor.physicsBody.applyForce(impulse, worldPoint);
  81280. };
  81281. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  81282. //parent-child relationship. Does this impostor has a parent impostor?
  81283. if (impostor.parent) {
  81284. if (impostor.physicsBody) {
  81285. this.removePhysicsBody(impostor);
  81286. //TODO is that needed?
  81287. impostor.forceUpdate();
  81288. }
  81289. return;
  81290. }
  81291. //should a new body be created for this impostor?
  81292. if (impostor.isBodyInitRequired()) {
  81293. var shape = this._createShape(impostor);
  81294. //unregister events, if body is being changed
  81295. var oldBody = impostor.physicsBody;
  81296. if (oldBody) {
  81297. this.removePhysicsBody(impostor);
  81298. }
  81299. //create the body and material
  81300. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  81301. var bodyCreationObject = {
  81302. mass: impostor.getParam("mass"),
  81303. material: material
  81304. };
  81305. // A simple extend, in case native options were used.
  81306. var nativeOptions = impostor.getParam("nativeOptions");
  81307. for (var key in nativeOptions) {
  81308. if (nativeOptions.hasOwnProperty(key)) {
  81309. bodyCreationObject[key] = nativeOptions[key];
  81310. }
  81311. }
  81312. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  81313. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  81314. this.world.addEventListener("preStep", impostor.beforeStep);
  81315. this.world.addEventListener("postStep", impostor.afterStep);
  81316. impostor.physicsBody.addShape(shape);
  81317. this.world.add(impostor.physicsBody);
  81318. //try to keep the body moving in the right direction by taking old properties.
  81319. //Should be tested!
  81320. if (oldBody) {
  81321. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  81322. impostor.physicsBody[param].copy(oldBody[param]);
  81323. });
  81324. }
  81325. this._processChildMeshes(impostor);
  81326. }
  81327. //now update the body's transformation
  81328. this._updatePhysicsBodyTransformation(impostor);
  81329. };
  81330. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  81331. var _this = this;
  81332. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  81333. var currentRotation = mainImpostor.object.rotationQuaternion;
  81334. if (meshChildren.length) {
  81335. var processMesh = function (localPosition, mesh) {
  81336. if (!currentRotation || !mesh.rotationQuaternion) {
  81337. return;
  81338. }
  81339. var childImpostor = mesh.getPhysicsImpostor();
  81340. if (childImpostor) {
  81341. var parent = childImpostor.parent;
  81342. if (parent !== mainImpostor) {
  81343. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  81344. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  81345. if (childImpostor.physicsBody) {
  81346. _this.removePhysicsBody(childImpostor);
  81347. childImpostor.physicsBody = null;
  81348. }
  81349. childImpostor.parent = mainImpostor;
  81350. childImpostor.resetUpdateFlags();
  81351. 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));
  81352. //Add the mass of the children.
  81353. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  81354. }
  81355. }
  81356. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  81357. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  81358. };
  81359. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  81360. }
  81361. };
  81362. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  81363. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  81364. this.world.removeEventListener("preStep", impostor.beforeStep);
  81365. this.world.removeEventListener("postStep", impostor.afterStep);
  81366. this.world.remove(impostor.physicsBody);
  81367. };
  81368. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  81369. var mainBody = impostorJoint.mainImpostor.physicsBody;
  81370. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  81371. if (!mainBody || !connectedBody) {
  81372. return;
  81373. }
  81374. var constraint;
  81375. var jointData = impostorJoint.joint.jointData;
  81376. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  81377. var constraintData = {
  81378. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  81379. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  81380. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  81381. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  81382. maxForce: jointData.nativeParams.maxForce,
  81383. collideConnected: !!jointData.collision
  81384. };
  81385. switch (impostorJoint.joint.type) {
  81386. case BABYLON.PhysicsJoint.HingeJoint:
  81387. case BABYLON.PhysicsJoint.Hinge2Joint:
  81388. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  81389. break;
  81390. case BABYLON.PhysicsJoint.DistanceJoint:
  81391. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  81392. break;
  81393. case BABYLON.PhysicsJoint.SpringJoint:
  81394. var springData = jointData;
  81395. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  81396. restLength: springData.length,
  81397. stiffness: springData.stiffness,
  81398. damping: springData.damping,
  81399. localAnchorA: constraintData.pivotA,
  81400. localAnchorB: constraintData.pivotB
  81401. });
  81402. break;
  81403. case BABYLON.PhysicsJoint.LockJoint:
  81404. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  81405. break;
  81406. case BABYLON.PhysicsJoint.PointToPointJoint:
  81407. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  81408. default:
  81409. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  81410. break;
  81411. }
  81412. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  81413. constraint.collideConnected = !!jointData.collision;
  81414. impostorJoint.joint.physicsJoint = constraint;
  81415. //don't add spring as constraint, as it is not one.
  81416. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  81417. this.world.addConstraint(constraint);
  81418. }
  81419. else {
  81420. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  81421. constraint.applyForce();
  81422. });
  81423. }
  81424. };
  81425. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  81426. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  81427. };
  81428. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  81429. var index;
  81430. var mat;
  81431. for (index = 0; index < this._physicsMaterials.length; index++) {
  81432. mat = this._physicsMaterials[index];
  81433. if (mat.friction === friction && mat.restitution === restitution) {
  81434. return mat;
  81435. }
  81436. }
  81437. var currentMat = new this.BJSCANNON.Material(name);
  81438. currentMat.friction = friction;
  81439. currentMat.restitution = restitution;
  81440. this._physicsMaterials.push(currentMat);
  81441. return currentMat;
  81442. };
  81443. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  81444. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  81445. };
  81446. CannonJSPlugin.prototype._createShape = function (impostor) {
  81447. var object = impostor.object;
  81448. var returnValue;
  81449. var extendSize = impostor.getObjectExtendSize();
  81450. switch (impostor.type) {
  81451. case BABYLON.PhysicsImpostor.SphereImpostor:
  81452. var radiusX = extendSize.x;
  81453. var radiusY = extendSize.y;
  81454. var radiusZ = extendSize.z;
  81455. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  81456. break;
  81457. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  81458. case BABYLON.PhysicsImpostor.CylinderImpostor:
  81459. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  81460. break;
  81461. case BABYLON.PhysicsImpostor.BoxImpostor:
  81462. var box = extendSize.scale(0.5);
  81463. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  81464. break;
  81465. case BABYLON.PhysicsImpostor.PlaneImpostor:
  81466. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  81467. returnValue = new this.BJSCANNON.Plane();
  81468. break;
  81469. case BABYLON.PhysicsImpostor.MeshImpostor:
  81470. // should transform the vertex data to world coordinates!!
  81471. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  81472. var rawFaces = object.getIndices ? object.getIndices() : [];
  81473. if (!rawVerts)
  81474. return;
  81475. // get only scale! so the object could transform correctly.
  81476. var oldPosition = object.position.clone();
  81477. var oldRotation = object.rotation && object.rotation.clone();
  81478. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  81479. object.position.copyFromFloats(0, 0, 0);
  81480. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  81481. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  81482. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  81483. var transform = object.computeWorldMatrix(true);
  81484. // convert rawVerts to object space
  81485. var temp = new Array();
  81486. var index;
  81487. for (index = 0; index < rawVerts.length; index += 3) {
  81488. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  81489. }
  81490. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  81491. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  81492. //now set back the transformation!
  81493. object.position.copyFrom(oldPosition);
  81494. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  81495. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  81496. break;
  81497. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  81498. var oldPosition2 = object.position.clone();
  81499. var oldRotation2 = object.rotation && object.rotation.clone();
  81500. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  81501. object.position.copyFromFloats(0, 0, 0);
  81502. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  81503. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  81504. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  81505. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  81506. returnValue = this._createHeightmap(object);
  81507. object.position.copyFrom(oldPosition2);
  81508. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  81509. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  81510. object.computeWorldMatrix(true);
  81511. break;
  81512. case BABYLON.PhysicsImpostor.ParticleImpostor:
  81513. returnValue = new this.BJSCANNON.Particle();
  81514. break;
  81515. }
  81516. return returnValue;
  81517. };
  81518. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  81519. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81520. var transform = object.computeWorldMatrix(true);
  81521. // convert rawVerts to object space
  81522. var temp = new Array();
  81523. var index;
  81524. for (index = 0; index < pos.length; index += 3) {
  81525. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  81526. }
  81527. pos = temp;
  81528. var matrix = new Array();
  81529. //For now pointDepth will not be used and will be automatically calculated.
  81530. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  81531. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  81532. var boundingInfo = object.getBoundingInfo();
  81533. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  81534. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  81535. var elementSize = dim * 2 / arraySize;
  81536. for (var i = 0; i < pos.length; i = i + 3) {
  81537. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  81538. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  81539. var y = -pos[i + 2] + minY;
  81540. if (!matrix[x]) {
  81541. matrix[x] = [];
  81542. }
  81543. if (!matrix[x][z]) {
  81544. matrix[x][z] = y;
  81545. }
  81546. matrix[x][z] = Math.max(y, matrix[x][z]);
  81547. }
  81548. for (var x = 0; x <= arraySize; ++x) {
  81549. if (!matrix[x]) {
  81550. var loc = 1;
  81551. while (!matrix[(x + loc) % arraySize]) {
  81552. loc++;
  81553. }
  81554. matrix[x] = matrix[(x + loc) % arraySize].slice();
  81555. //console.log("missing x", x);
  81556. }
  81557. for (var z = 0; z <= arraySize; ++z) {
  81558. if (!matrix[x][z]) {
  81559. var loc = 1;
  81560. var newValue;
  81561. while (newValue === undefined) {
  81562. newValue = matrix[x][(z + loc++) % arraySize];
  81563. }
  81564. matrix[x][z] = newValue;
  81565. }
  81566. }
  81567. }
  81568. var shape = new this.BJSCANNON.Heightfield(matrix, {
  81569. elementSize: elementSize
  81570. });
  81571. //For future reference, needed for body transformation
  81572. shape.minY = minY;
  81573. return shape;
  81574. };
  81575. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  81576. var object = impostor.object;
  81577. //make sure it is updated...
  81578. object.computeWorldMatrix && object.computeWorldMatrix(true);
  81579. // The delta between the mesh position and the mesh bounding box center
  81580. var bInfo = object.getBoundingInfo();
  81581. if (!bInfo)
  81582. return;
  81583. var center = impostor.getObjectCenter();
  81584. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  81585. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  81586. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  81587. this._tmpPosition.copyFrom(center);
  81588. var quaternion = object.rotationQuaternion;
  81589. if (!quaternion) {
  81590. return;
  81591. }
  81592. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  81593. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  81594. //-90 DEG in X, precalculated
  81595. quaternion = quaternion.multiply(this._minus90X);
  81596. //Invert! (Precalculated, 90 deg in X)
  81597. //No need to clone. this will never change.
  81598. impostor.setDeltaRotation(this._plus90X);
  81599. }
  81600. //If it is a heightfield, if should be centered.
  81601. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  81602. var mesh = object;
  81603. var boundingInfo = mesh.getBoundingInfo();
  81604. //calculate the correct body position:
  81605. var rotationQuaternion = mesh.rotationQuaternion;
  81606. mesh.rotationQuaternion = this._tmpUnityRotation;
  81607. mesh.computeWorldMatrix(true);
  81608. //get original center with no rotation
  81609. var c = center.clone();
  81610. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  81611. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  81612. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  81613. mesh.setPreTransformMatrix(p);
  81614. mesh.computeWorldMatrix(true);
  81615. //calculate the translation
  81616. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  81617. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  81618. //add it inverted to the delta
  81619. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  81620. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  81621. //rotation is back
  81622. mesh.rotationQuaternion = rotationQuaternion;
  81623. mesh.setPreTransformMatrix(oldPivot);
  81624. mesh.computeWorldMatrix(true);
  81625. }
  81626. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  81627. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  81628. //this._tmpPosition.copyFrom(object.position);
  81629. }
  81630. impostor.setDeltaPosition(this._tmpDeltaPosition);
  81631. //Now update the impostor object
  81632. impostor.physicsBody.position.copy(this._tmpPosition);
  81633. impostor.physicsBody.quaternion.copy(quaternion);
  81634. };
  81635. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  81636. impostor.object.position.copyFrom(impostor.physicsBody.position);
  81637. if (impostor.object.rotationQuaternion) {
  81638. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  81639. }
  81640. };
  81641. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  81642. impostor.physicsBody.position.copy(newPosition);
  81643. impostor.physicsBody.quaternion.copy(newRotation);
  81644. };
  81645. CannonJSPlugin.prototype.isSupported = function () {
  81646. return this.BJSCANNON !== undefined;
  81647. };
  81648. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  81649. impostor.physicsBody.velocity.copy(velocity);
  81650. };
  81651. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  81652. impostor.physicsBody.angularVelocity.copy(velocity);
  81653. };
  81654. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  81655. var v = impostor.physicsBody.velocity;
  81656. if (!v) {
  81657. return null;
  81658. }
  81659. return new BABYLON.Vector3(v.x, v.y, v.z);
  81660. };
  81661. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  81662. var v = impostor.physicsBody.angularVelocity;
  81663. if (!v) {
  81664. return null;
  81665. }
  81666. return new BABYLON.Vector3(v.x, v.y, v.z);
  81667. };
  81668. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  81669. impostor.physicsBody.mass = mass;
  81670. impostor.physicsBody.updateMassProperties();
  81671. };
  81672. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  81673. return impostor.physicsBody.mass;
  81674. };
  81675. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  81676. return impostor.physicsBody.material.friction;
  81677. };
  81678. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  81679. impostor.physicsBody.material.friction = friction;
  81680. };
  81681. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  81682. return impostor.physicsBody.material.restitution;
  81683. };
  81684. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  81685. impostor.physicsBody.material.restitution = restitution;
  81686. };
  81687. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  81688. impostor.physicsBody.sleep();
  81689. };
  81690. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  81691. impostor.physicsBody.wakeUp();
  81692. };
  81693. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  81694. joint.physicsJoint.distance = maxDistance;
  81695. };
  81696. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  81697. // if (!motorIndex) {
  81698. // joint.physicsJoint.enableMotor();
  81699. // }
  81700. // }
  81701. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  81702. // if (!motorIndex) {
  81703. // joint.physicsJoint.disableMotor();
  81704. // }
  81705. // }
  81706. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  81707. if (!motorIndex) {
  81708. joint.physicsJoint.enableMotor();
  81709. joint.physicsJoint.setMotorSpeed(speed);
  81710. if (maxForce) {
  81711. this.setLimit(joint, maxForce);
  81712. }
  81713. }
  81714. };
  81715. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  81716. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  81717. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  81718. };
  81719. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  81720. var body = impostor.physicsBody;
  81721. mesh.position.x = body.position.x;
  81722. mesh.position.y = body.position.y;
  81723. mesh.position.z = body.position.z;
  81724. if (mesh.rotationQuaternion) {
  81725. mesh.rotationQuaternion.x = body.quaternion.x;
  81726. mesh.rotationQuaternion.y = body.quaternion.y;
  81727. mesh.rotationQuaternion.z = body.quaternion.z;
  81728. mesh.rotationQuaternion.w = body.quaternion.w;
  81729. }
  81730. };
  81731. CannonJSPlugin.prototype.getRadius = function (impostor) {
  81732. var shape = impostor.physicsBody.shapes[0];
  81733. return shape.boundingSphereRadius;
  81734. };
  81735. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  81736. var shape = impostor.physicsBody.shapes[0];
  81737. result.x = shape.halfExtents.x * 2;
  81738. result.y = shape.halfExtents.y * 2;
  81739. result.z = shape.halfExtents.z * 2;
  81740. };
  81741. CannonJSPlugin.prototype.dispose = function () {
  81742. };
  81743. CannonJSPlugin.prototype._extendNamespace = function () {
  81744. //this will force cannon to execute at least one step when using interpolation
  81745. var step_tmp1 = new this.BJSCANNON.Vec3();
  81746. var Engine = this.BJSCANNON;
  81747. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  81748. maxSubSteps = maxSubSteps || 10;
  81749. timeSinceLastCalled = timeSinceLastCalled || 0;
  81750. if (timeSinceLastCalled === 0) {
  81751. this.internalStep(dt);
  81752. this.time += dt;
  81753. }
  81754. else {
  81755. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  81756. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  81757. var t0 = performance.now();
  81758. for (var i = 0; i !== internalSteps; i++) {
  81759. this.internalStep(dt);
  81760. if (performance.now() - t0 > dt * 1000) {
  81761. break;
  81762. }
  81763. }
  81764. this.time += timeSinceLastCalled;
  81765. var h = this.time % dt;
  81766. var h_div_dt = h / dt;
  81767. var interpvelo = step_tmp1;
  81768. var bodies = this.bodies;
  81769. for (var j = 0; j !== bodies.length; j++) {
  81770. var b = bodies[j];
  81771. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  81772. b.position.vsub(b.previousPosition, interpvelo);
  81773. interpvelo.scale(h_div_dt, interpvelo);
  81774. b.position.vadd(interpvelo, b.interpolatedPosition);
  81775. }
  81776. else {
  81777. b.interpolatedPosition.copy(b.position);
  81778. b.interpolatedQuaternion.copy(b.quaternion);
  81779. }
  81780. }
  81781. }
  81782. };
  81783. };
  81784. return CannonJSPlugin;
  81785. }());
  81786. BABYLON.CannonJSPlugin = CannonJSPlugin;
  81787. })(BABYLON || (BABYLON = {}));
  81788. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  81789. "use strict";
  81790. var BABYLON;
  81791. (function (BABYLON) {
  81792. var OimoJSPlugin = /** @class */ (function () {
  81793. function OimoJSPlugin(iterations) {
  81794. this.name = "OimoJSPlugin";
  81795. this._tmpImpostorsArray = [];
  81796. this._tmpPositionVector = BABYLON.Vector3.Zero();
  81797. this.BJSOIMO = OIMO;
  81798. this.world = new this.BJSOIMO.World({
  81799. iterations: iterations
  81800. });
  81801. this.world.clear();
  81802. }
  81803. OimoJSPlugin.prototype.setGravity = function (gravity) {
  81804. this.world.gravity.copy(gravity);
  81805. };
  81806. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  81807. this.world.timeStep = timeStep;
  81808. };
  81809. OimoJSPlugin.prototype.getTimeStep = function () {
  81810. return this.world.timeStep;
  81811. };
  81812. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  81813. var _this = this;
  81814. impostors.forEach(function (impostor) {
  81815. impostor.beforeStep();
  81816. });
  81817. this.world.step();
  81818. impostors.forEach(function (impostor) {
  81819. impostor.afterStep();
  81820. //update the ordered impostors array
  81821. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  81822. });
  81823. //check for collisions
  81824. var contact = this.world.contacts;
  81825. while (contact !== null) {
  81826. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  81827. contact = contact.next;
  81828. continue;
  81829. }
  81830. //is this body colliding with any other? get the impostor
  81831. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  81832. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  81833. if (!mainImpostor || !collidingImpostor) {
  81834. contact = contact.next;
  81835. continue;
  81836. }
  81837. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  81838. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  81839. contact = contact.next;
  81840. }
  81841. };
  81842. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  81843. var mass = impostor.physicsBody.mass;
  81844. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  81845. };
  81846. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  81847. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  81848. this.applyImpulse(impostor, force, contactPoint);
  81849. };
  81850. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  81851. var _this = this;
  81852. //parent-child relationship. Does this impostor has a parent impostor?
  81853. if (impostor.parent) {
  81854. if (impostor.physicsBody) {
  81855. this.removePhysicsBody(impostor);
  81856. //TODO is that needed?
  81857. impostor.forceUpdate();
  81858. }
  81859. return;
  81860. }
  81861. if (impostor.isBodyInitRequired()) {
  81862. var bodyConfig = {
  81863. name: impostor.uniqueId,
  81864. //Oimo must have mass, also for static objects.
  81865. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  81866. size: [],
  81867. type: [],
  81868. pos: [],
  81869. posShape: [],
  81870. rot: [],
  81871. rotShape: [],
  81872. move: impostor.getParam("mass") !== 0,
  81873. density: impostor.getParam("mass"),
  81874. friction: impostor.getParam("friction"),
  81875. restitution: impostor.getParam("restitution"),
  81876. //Supporting older versions of Oimo
  81877. world: this.world
  81878. };
  81879. var impostors = [impostor];
  81880. var addToArray = function (parent) {
  81881. if (!parent.getChildMeshes)
  81882. return;
  81883. parent.getChildMeshes().forEach(function (m) {
  81884. if (m.physicsImpostor) {
  81885. impostors.push(m.physicsImpostor);
  81886. //m.physicsImpostor._init();
  81887. }
  81888. });
  81889. };
  81890. addToArray(impostor.object);
  81891. var checkWithEpsilon_1 = function (value) {
  81892. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  81893. };
  81894. impostors.forEach(function (i) {
  81895. if (!i.object.rotationQuaternion) {
  81896. return;
  81897. }
  81898. //get the correct bounding box
  81899. var oldQuaternion = i.object.rotationQuaternion;
  81900. var rot = oldQuaternion.toEulerAngles();
  81901. var extendSize = i.getObjectExtendSize();
  81902. var radToDeg = 57.295779513082320876;
  81903. if (i === impostor) {
  81904. var center = impostor.getObjectCenter();
  81905. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  81906. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  81907. //Can also use Array.prototype.push.apply
  81908. bodyConfig.pos.push(center.x);
  81909. bodyConfig.pos.push(center.y);
  81910. bodyConfig.pos.push(center.z);
  81911. bodyConfig.posShape.push(0, 0, 0);
  81912. //tmp solution
  81913. bodyConfig.rot.push(rot.x * radToDeg);
  81914. bodyConfig.rot.push(rot.y * radToDeg);
  81915. bodyConfig.rot.push(rot.z * radToDeg);
  81916. bodyConfig.rotShape.push(0, 0, 0);
  81917. }
  81918. else {
  81919. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  81920. bodyConfig.posShape.push(localPosition.x);
  81921. bodyConfig.posShape.push(localPosition.y);
  81922. bodyConfig.posShape.push(localPosition.z);
  81923. bodyConfig.pos.push(0, 0, 0);
  81924. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  81925. bodyConfig.rot.push(0);
  81926. bodyConfig.rot.push(0);
  81927. bodyConfig.rot.push(0);
  81928. bodyConfig.rotShape.push(rot.x * radToDeg);
  81929. bodyConfig.rotShape.push(rot.y * radToDeg);
  81930. bodyConfig.rotShape.push(rot.z * radToDeg);
  81931. }
  81932. // register mesh
  81933. switch (i.type) {
  81934. case BABYLON.PhysicsImpostor.ParticleImpostor:
  81935. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  81936. case BABYLON.PhysicsImpostor.SphereImpostor:
  81937. var radiusX = extendSize.x;
  81938. var radiusY = extendSize.y;
  81939. var radiusZ = extendSize.z;
  81940. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  81941. bodyConfig.type.push('sphere');
  81942. //due to the way oimo works with compounds, add 3 times
  81943. bodyConfig.size.push(size);
  81944. bodyConfig.size.push(size);
  81945. bodyConfig.size.push(size);
  81946. break;
  81947. case BABYLON.PhysicsImpostor.CylinderImpostor:
  81948. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  81949. var sizeY = checkWithEpsilon_1(extendSize.y);
  81950. bodyConfig.type.push('cylinder');
  81951. bodyConfig.size.push(sizeX);
  81952. bodyConfig.size.push(sizeY);
  81953. //due to the way oimo works with compounds, add one more value.
  81954. bodyConfig.size.push(sizeY);
  81955. break;
  81956. case BABYLON.PhysicsImpostor.PlaneImpostor:
  81957. case BABYLON.PhysicsImpostor.BoxImpostor:
  81958. default:
  81959. var sizeX = checkWithEpsilon_1(extendSize.x);
  81960. var sizeY = checkWithEpsilon_1(extendSize.y);
  81961. var sizeZ = checkWithEpsilon_1(extendSize.z);
  81962. bodyConfig.type.push('box');
  81963. //if (i === impostor) {
  81964. bodyConfig.size.push(sizeX);
  81965. bodyConfig.size.push(sizeY);
  81966. bodyConfig.size.push(sizeZ);
  81967. //} else {
  81968. // bodyConfig.size.push(0,0,0);
  81969. //}
  81970. break;
  81971. }
  81972. //actually not needed, but hey...
  81973. i.object.rotationQuaternion = oldQuaternion;
  81974. });
  81975. impostor.physicsBody = this.world.add(bodyConfig);
  81976. }
  81977. else {
  81978. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  81979. }
  81980. impostor.setDeltaPosition(this._tmpPositionVector);
  81981. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  81982. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  81983. };
  81984. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  81985. //impostor.physicsBody.dispose();
  81986. //Same as : (older oimo versions)
  81987. this.world.removeRigidBody(impostor.physicsBody);
  81988. };
  81989. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  81990. var mainBody = impostorJoint.mainImpostor.physicsBody;
  81991. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  81992. if (!mainBody || !connectedBody) {
  81993. return;
  81994. }
  81995. var jointData = impostorJoint.joint.jointData;
  81996. var options = jointData.nativeParams || {};
  81997. var type;
  81998. var nativeJointData = {
  81999. body1: mainBody,
  82000. body2: connectedBody,
  82001. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  82002. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  82003. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  82004. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  82005. min: options.min,
  82006. max: options.max,
  82007. collision: options.collision || jointData.collision,
  82008. spring: options.spring,
  82009. //supporting older version of Oimo
  82010. world: this.world
  82011. };
  82012. switch (impostorJoint.joint.type) {
  82013. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  82014. type = "jointBall";
  82015. break;
  82016. case BABYLON.PhysicsJoint.SpringJoint:
  82017. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  82018. var springData = jointData;
  82019. nativeJointData.min = springData.length || nativeJointData.min;
  82020. //Max should also be set, just make sure it is at least min
  82021. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  82022. case BABYLON.PhysicsJoint.DistanceJoint:
  82023. type = "jointDistance";
  82024. nativeJointData.max = jointData.maxDistance;
  82025. break;
  82026. case BABYLON.PhysicsJoint.PrismaticJoint:
  82027. type = "jointPrisme";
  82028. break;
  82029. case BABYLON.PhysicsJoint.SliderJoint:
  82030. type = "jointSlide";
  82031. break;
  82032. case BABYLON.PhysicsJoint.WheelJoint:
  82033. type = "jointWheel";
  82034. break;
  82035. case BABYLON.PhysicsJoint.HingeJoint:
  82036. default:
  82037. type = "jointHinge";
  82038. break;
  82039. }
  82040. nativeJointData.type = type;
  82041. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  82042. };
  82043. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  82044. //Bug in Oimo prevents us from disposing a joint in the playground
  82045. //joint.joint.physicsJoint.dispose();
  82046. //So we will bruteforce it!
  82047. try {
  82048. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  82049. }
  82050. catch (e) {
  82051. BABYLON.Tools.Warn(e);
  82052. }
  82053. };
  82054. OimoJSPlugin.prototype.isSupported = function () {
  82055. return this.BJSOIMO !== undefined;
  82056. };
  82057. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82058. if (!impostor.physicsBody.sleeping) {
  82059. //TODO check that
  82060. /*if (impostor.physicsBody.shapes.next) {
  82061. var parentShape = this._getLastShape(impostor.physicsBody);
  82062. impostor.object.position.copyFrom(parentShape.position);
  82063. console.log(parentShape.position);
  82064. } else {*/
  82065. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  82066. //}
  82067. if (impostor.object.rotationQuaternion) {
  82068. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  82069. }
  82070. }
  82071. };
  82072. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82073. var body = impostor.physicsBody;
  82074. body.position.copy(newPosition);
  82075. body.orientation.copy(newRotation);
  82076. body.syncShapes();
  82077. body.awake();
  82078. };
  82079. /*private _getLastShape(body: any): any {
  82080. var lastShape = body.shapes;
  82081. while (lastShape.next) {
  82082. lastShape = lastShape.next;
  82083. }
  82084. return lastShape;
  82085. }*/
  82086. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82087. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  82088. };
  82089. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82090. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  82091. };
  82092. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82093. var v = impostor.physicsBody.linearVelocity;
  82094. if (!v) {
  82095. return null;
  82096. }
  82097. return new BABYLON.Vector3(v.x, v.y, v.z);
  82098. };
  82099. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82100. var v = impostor.physicsBody.angularVelocity;
  82101. if (!v) {
  82102. return null;
  82103. }
  82104. return new BABYLON.Vector3(v.x, v.y, v.z);
  82105. };
  82106. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82107. var staticBody = mass === 0;
  82108. //this will actually set the body's density and not its mass.
  82109. //But this is how oimo treats the mass variable.
  82110. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  82111. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  82112. };
  82113. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  82114. return impostor.physicsBody.shapes.density;
  82115. };
  82116. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  82117. return impostor.physicsBody.shapes.friction;
  82118. };
  82119. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82120. impostor.physicsBody.shapes.friction = friction;
  82121. };
  82122. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82123. return impostor.physicsBody.shapes.restitution;
  82124. };
  82125. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82126. impostor.physicsBody.shapes.restitution = restitution;
  82127. };
  82128. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  82129. impostor.physicsBody.sleep();
  82130. };
  82131. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  82132. impostor.physicsBody.awake();
  82133. };
  82134. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82135. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  82136. if (minDistance !== void 0) {
  82137. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  82138. }
  82139. };
  82140. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82141. //TODO separate rotational and transational motors.
  82142. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  82143. if (motor) {
  82144. motor.setMotor(speed, maxForce);
  82145. }
  82146. };
  82147. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  82148. //TODO separate rotational and transational motors.
  82149. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  82150. if (motor) {
  82151. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  82152. }
  82153. };
  82154. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  82155. var body = impostor.physicsBody;
  82156. mesh.position.x = body.position.x;
  82157. mesh.position.y = body.position.y;
  82158. mesh.position.z = body.position.z;
  82159. if (mesh.rotationQuaternion) {
  82160. mesh.rotationQuaternion.x = body.orientation.x;
  82161. mesh.rotationQuaternion.y = body.orientation.y;
  82162. mesh.rotationQuaternion.z = body.orientation.z;
  82163. mesh.rotationQuaternion.w = body.orientation.s;
  82164. }
  82165. };
  82166. OimoJSPlugin.prototype.getRadius = function (impostor) {
  82167. return impostor.physicsBody.shapes.radius;
  82168. };
  82169. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  82170. var shape = impostor.physicsBody.shapes;
  82171. result.x = shape.halfWidth * 2;
  82172. result.y = shape.halfHeight * 2;
  82173. result.z = shape.halfDepth * 2;
  82174. };
  82175. OimoJSPlugin.prototype.dispose = function () {
  82176. this.world.clear();
  82177. };
  82178. return OimoJSPlugin;
  82179. }());
  82180. BABYLON.OimoJSPlugin = OimoJSPlugin;
  82181. })(BABYLON || (BABYLON = {}));
  82182. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  82183. "use strict";
  82184. var BABYLON;
  82185. (function (BABYLON) {
  82186. /*
  82187. * Based on jsTGALoader - Javascript loader for TGA file
  82188. * By Vincent Thibault
  82189. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  82190. */
  82191. var TGATools = /** @class */ (function () {
  82192. function TGATools() {
  82193. }
  82194. TGATools.GetTGAHeader = function (data) {
  82195. var offset = 0;
  82196. var header = {
  82197. id_length: data[offset++],
  82198. colormap_type: data[offset++],
  82199. image_type: data[offset++],
  82200. colormap_index: data[offset++] | data[offset++] << 8,
  82201. colormap_length: data[offset++] | data[offset++] << 8,
  82202. colormap_size: data[offset++],
  82203. origin: [
  82204. data[offset++] | data[offset++] << 8,
  82205. data[offset++] | data[offset++] << 8
  82206. ],
  82207. width: data[offset++] | data[offset++] << 8,
  82208. height: data[offset++] | data[offset++] << 8,
  82209. pixel_size: data[offset++],
  82210. flags: data[offset++]
  82211. };
  82212. return header;
  82213. };
  82214. TGATools.UploadContent = function (gl, data) {
  82215. // Not enough data to contain header ?
  82216. if (data.length < 19) {
  82217. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  82218. return;
  82219. }
  82220. // Read Header
  82221. var offset = 18;
  82222. var header = TGATools.GetTGAHeader(data);
  82223. // Assume it's a valid Targa file.
  82224. if (header.id_length + offset > data.length) {
  82225. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  82226. return;
  82227. }
  82228. // Skip not needed data
  82229. offset += header.id_length;
  82230. var use_rle = false;
  82231. var use_pal = false;
  82232. var use_grey = false;
  82233. // Get some informations.
  82234. switch (header.image_type) {
  82235. case TGATools._TYPE_RLE_INDEXED:
  82236. use_rle = true;
  82237. case TGATools._TYPE_INDEXED:
  82238. use_pal = true;
  82239. break;
  82240. case TGATools._TYPE_RLE_RGB:
  82241. use_rle = true;
  82242. case TGATools._TYPE_RGB:
  82243. // use_rgb = true;
  82244. break;
  82245. case TGATools._TYPE_RLE_GREY:
  82246. use_rle = true;
  82247. case TGATools._TYPE_GREY:
  82248. use_grey = true;
  82249. break;
  82250. }
  82251. var pixel_data;
  82252. // var numAlphaBits = header.flags & 0xf;
  82253. var pixel_size = header.pixel_size >> 3;
  82254. var pixel_total = header.width * header.height * pixel_size;
  82255. // Read palettes
  82256. var palettes;
  82257. if (use_pal) {
  82258. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  82259. }
  82260. // Read LRE
  82261. if (use_rle) {
  82262. pixel_data = new Uint8Array(pixel_total);
  82263. var c, count, i;
  82264. var localOffset = 0;
  82265. var pixels = new Uint8Array(pixel_size);
  82266. while (offset < pixel_total && localOffset < pixel_total) {
  82267. c = data[offset++];
  82268. count = (c & 0x7f) + 1;
  82269. // RLE pixels
  82270. if (c & 0x80) {
  82271. // Bind pixel tmp array
  82272. for (i = 0; i < pixel_size; ++i) {
  82273. pixels[i] = data[offset++];
  82274. }
  82275. // Copy pixel array
  82276. for (i = 0; i < count; ++i) {
  82277. pixel_data.set(pixels, localOffset + i * pixel_size);
  82278. }
  82279. localOffset += pixel_size * count;
  82280. }
  82281. else {
  82282. count *= pixel_size;
  82283. for (i = 0; i < count; ++i) {
  82284. pixel_data[localOffset + i] = data[offset++];
  82285. }
  82286. localOffset += count;
  82287. }
  82288. }
  82289. }
  82290. else {
  82291. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  82292. }
  82293. // Load to texture
  82294. var x_start, y_start, x_step, y_step, y_end, x_end;
  82295. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  82296. default:
  82297. case TGATools._ORIGIN_UL:
  82298. x_start = 0;
  82299. x_step = 1;
  82300. x_end = header.width;
  82301. y_start = 0;
  82302. y_step = 1;
  82303. y_end = header.height;
  82304. break;
  82305. case TGATools._ORIGIN_BL:
  82306. x_start = 0;
  82307. x_step = 1;
  82308. x_end = header.width;
  82309. y_start = header.height - 1;
  82310. y_step = -1;
  82311. y_end = -1;
  82312. break;
  82313. case TGATools._ORIGIN_UR:
  82314. x_start = header.width - 1;
  82315. x_step = -1;
  82316. x_end = -1;
  82317. y_start = 0;
  82318. y_step = 1;
  82319. y_end = header.height;
  82320. break;
  82321. case TGATools._ORIGIN_BR:
  82322. x_start = header.width - 1;
  82323. x_step = -1;
  82324. x_end = -1;
  82325. y_start = header.height - 1;
  82326. y_step = -1;
  82327. y_end = -1;
  82328. break;
  82329. }
  82330. // Load the specify method
  82331. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  82332. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  82333. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  82334. };
  82335. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82336. var image = pixel_data, colormap = palettes;
  82337. var width = header.width, height = header.height;
  82338. var color, i = 0, x, y;
  82339. var imageData = new Uint8Array(width * height * 4);
  82340. for (y = y_start; y !== y_end; y += y_step) {
  82341. for (x = x_start; x !== x_end; x += x_step, i++) {
  82342. color = image[i];
  82343. imageData[(x + width * y) * 4 + 3] = 255;
  82344. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  82345. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  82346. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  82347. }
  82348. }
  82349. return imageData;
  82350. };
  82351. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82352. var image = pixel_data;
  82353. var width = header.width, height = header.height;
  82354. var color, i = 0, x, y;
  82355. var imageData = new Uint8Array(width * height * 4);
  82356. for (y = y_start; y !== y_end; y += y_step) {
  82357. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  82358. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  82359. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  82360. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  82361. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  82362. imageData[(x + width * y) * 4 + 0] = r;
  82363. imageData[(x + width * y) * 4 + 1] = g;
  82364. imageData[(x + width * y) * 4 + 2] = b;
  82365. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  82366. }
  82367. }
  82368. return imageData;
  82369. };
  82370. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82371. var image = pixel_data;
  82372. var width = header.width, height = header.height;
  82373. var i = 0, x, y;
  82374. var imageData = new Uint8Array(width * height * 4);
  82375. for (y = y_start; y !== y_end; y += y_step) {
  82376. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  82377. imageData[(x + width * y) * 4 + 3] = 255;
  82378. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82379. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  82380. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  82381. }
  82382. }
  82383. return imageData;
  82384. };
  82385. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82386. var image = pixel_data;
  82387. var width = header.width, height = header.height;
  82388. var i = 0, x, y;
  82389. var imageData = new Uint8Array(width * height * 4);
  82390. for (y = y_start; y !== y_end; y += y_step) {
  82391. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  82392. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82393. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  82394. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  82395. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  82396. }
  82397. }
  82398. return imageData;
  82399. };
  82400. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82401. var image = pixel_data;
  82402. var width = header.width, height = header.height;
  82403. var color, i = 0, x, y;
  82404. var imageData = new Uint8Array(width * height * 4);
  82405. for (y = y_start; y !== y_end; y += y_step) {
  82406. for (x = x_start; x !== x_end; x += x_step, i++) {
  82407. color = image[i];
  82408. imageData[(x + width * y) * 4 + 0] = color;
  82409. imageData[(x + width * y) * 4 + 1] = color;
  82410. imageData[(x + width * y) * 4 + 2] = color;
  82411. imageData[(x + width * y) * 4 + 3] = 255;
  82412. }
  82413. }
  82414. return imageData;
  82415. };
  82416. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82417. var image = pixel_data;
  82418. var width = header.width, height = header.height;
  82419. var i = 0, x, y;
  82420. var imageData = new Uint8Array(width * height * 4);
  82421. for (y = y_start; y !== y_end; y += y_step) {
  82422. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  82423. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  82424. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  82425. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82426. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  82427. }
  82428. }
  82429. return imageData;
  82430. };
  82431. //private static _TYPE_NO_DATA = 0;
  82432. TGATools._TYPE_INDEXED = 1;
  82433. TGATools._TYPE_RGB = 2;
  82434. TGATools._TYPE_GREY = 3;
  82435. TGATools._TYPE_RLE_INDEXED = 9;
  82436. TGATools._TYPE_RLE_RGB = 10;
  82437. TGATools._TYPE_RLE_GREY = 11;
  82438. TGATools._ORIGIN_MASK = 0x30;
  82439. TGATools._ORIGIN_SHIFT = 0x04;
  82440. TGATools._ORIGIN_BL = 0x00;
  82441. TGATools._ORIGIN_BR = 0x01;
  82442. TGATools._ORIGIN_UL = 0x02;
  82443. TGATools._ORIGIN_UR = 0x03;
  82444. return TGATools;
  82445. }());
  82446. BABYLON.TGATools = TGATools;
  82447. })(BABYLON || (BABYLON = {}));
  82448. //# sourceMappingURL=babylon.tga.js.map
  82449. "use strict";
  82450. var BABYLON;
  82451. (function (BABYLON) {
  82452. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  82453. // All values and structures referenced from:
  82454. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  82455. var DDS_MAGIC = 0x20534444;
  82456. var
  82457. //DDSD_CAPS = 0x1,
  82458. //DDSD_HEIGHT = 0x2,
  82459. //DDSD_WIDTH = 0x4,
  82460. //DDSD_PITCH = 0x8,
  82461. //DDSD_PIXELFORMAT = 0x1000,
  82462. DDSD_MIPMAPCOUNT = 0x20000;
  82463. //DDSD_LINEARSIZE = 0x80000,
  82464. //DDSD_DEPTH = 0x800000;
  82465. // var DDSCAPS_COMPLEX = 0x8,
  82466. // DDSCAPS_MIPMAP = 0x400000,
  82467. // DDSCAPS_TEXTURE = 0x1000;
  82468. var DDSCAPS2_CUBEMAP = 0x200;
  82469. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  82470. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  82471. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  82472. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  82473. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  82474. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  82475. // DDSCAPS2_VOLUME = 0x200000;
  82476. var
  82477. //DDPF_ALPHAPIXELS = 0x1,
  82478. //DDPF_ALPHA = 0x2,
  82479. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  82480. //DDPF_YUV = 0x200,
  82481. DDPF_LUMINANCE = 0x20000;
  82482. function FourCCToInt32(value) {
  82483. return value.charCodeAt(0) +
  82484. (value.charCodeAt(1) << 8) +
  82485. (value.charCodeAt(2) << 16) +
  82486. (value.charCodeAt(3) << 24);
  82487. }
  82488. function Int32ToFourCC(value) {
  82489. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  82490. }
  82491. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  82492. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  82493. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  82494. var FOURCC_DX10 = FourCCToInt32("DX10");
  82495. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  82496. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  82497. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  82498. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  82499. var headerLengthInt = 31; // The header length in 32 bit ints
  82500. // Offsets into the header array
  82501. var off_magic = 0;
  82502. var off_size = 1;
  82503. var off_flags = 2;
  82504. var off_height = 3;
  82505. var off_width = 4;
  82506. var off_mipmapCount = 7;
  82507. var off_pfFlags = 20;
  82508. var off_pfFourCC = 21;
  82509. var off_RGBbpp = 22;
  82510. var off_RMask = 23;
  82511. var off_GMask = 24;
  82512. var off_BMask = 25;
  82513. var off_AMask = 26;
  82514. // var off_caps1 = 27;
  82515. var off_caps2 = 28;
  82516. // var off_caps3 = 29;
  82517. // var off_caps4 = 30;
  82518. var off_dxgiFormat = 32;
  82519. ;
  82520. var DDSTools = /** @class */ (function () {
  82521. function DDSTools() {
  82522. }
  82523. DDSTools.GetDDSInfo = function (arrayBuffer) {
  82524. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  82525. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  82526. var mipmapCount = 1;
  82527. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  82528. mipmapCount = Math.max(1, header[off_mipmapCount]);
  82529. }
  82530. var fourCC = header[off_pfFourCC];
  82531. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  82532. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82533. switch (fourCC) {
  82534. case FOURCC_D3DFMT_R16G16B16A16F:
  82535. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82536. break;
  82537. case FOURCC_D3DFMT_R32G32B32A32F:
  82538. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82539. break;
  82540. case FOURCC_DX10:
  82541. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  82542. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82543. break;
  82544. }
  82545. }
  82546. return {
  82547. width: header[off_width],
  82548. height: header[off_height],
  82549. mipmapCount: mipmapCount,
  82550. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  82551. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  82552. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  82553. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  82554. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  82555. dxgiFormat: dxgiFormat,
  82556. textureType: textureType
  82557. };
  82558. };
  82559. DDSTools._ToHalfFloat = function (value) {
  82560. if (!DDSTools._FloatView) {
  82561. DDSTools._FloatView = new Float32Array(1);
  82562. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  82563. }
  82564. DDSTools._FloatView[0] = value;
  82565. var x = DDSTools._Int32View[0];
  82566. var bits = (x >> 16) & 0x8000; /* Get the sign */
  82567. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  82568. var e = (x >> 23) & 0xff; /* Using int is faster here */
  82569. /* If zero, or denormal, or exponent underflows too much for a denormal
  82570. * half, return signed zero. */
  82571. if (e < 103) {
  82572. return bits;
  82573. }
  82574. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  82575. if (e > 142) {
  82576. bits |= 0x7c00;
  82577. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  82578. * not Inf, so make sure we set one mantissa bit too. */
  82579. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  82580. return bits;
  82581. }
  82582. /* If exponent underflows but not too much, return a denormal */
  82583. if (e < 113) {
  82584. m |= 0x0800;
  82585. /* Extra rounding may overflow and set mantissa to 0 and exponent
  82586. * to 1, which is OK. */
  82587. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  82588. return bits;
  82589. }
  82590. bits |= ((e - 112) << 10) | (m >> 1);
  82591. bits += m & 1;
  82592. return bits;
  82593. };
  82594. DDSTools._FromHalfFloat = function (value) {
  82595. var s = (value & 0x8000) >> 15;
  82596. var e = (value & 0x7C00) >> 10;
  82597. var f = value & 0x03FF;
  82598. if (e === 0) {
  82599. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  82600. }
  82601. else if (e == 0x1F) {
  82602. return f ? NaN : ((s ? -1 : 1) * Infinity);
  82603. }
  82604. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  82605. };
  82606. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82607. var destArray = new Float32Array(dataLength);
  82608. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82609. var index = 0;
  82610. for (var y = 0; y < height; y++) {
  82611. for (var x = 0; x < width; x++) {
  82612. var srcPos = (x + y * width) * 4;
  82613. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  82614. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  82615. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  82616. if (DDSTools.StoreLODInAlphaChannel) {
  82617. destArray[index + 3] = lod;
  82618. }
  82619. else {
  82620. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  82621. }
  82622. index += 4;
  82623. }
  82624. }
  82625. return destArray;
  82626. };
  82627. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82628. if (DDSTools.StoreLODInAlphaChannel) {
  82629. var destArray = new Uint16Array(dataLength);
  82630. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82631. var index = 0;
  82632. for (var y = 0; y < height; y++) {
  82633. for (var x = 0; x < width; x++) {
  82634. var srcPos = (x + y * width) * 4;
  82635. destArray[index] = srcData[srcPos];
  82636. destArray[index + 1] = srcData[srcPos + 1];
  82637. destArray[index + 2] = srcData[srcPos + 2];
  82638. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  82639. index += 4;
  82640. }
  82641. }
  82642. return destArray;
  82643. }
  82644. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  82645. };
  82646. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82647. if (DDSTools.StoreLODInAlphaChannel) {
  82648. var destArray = new Float32Array(dataLength);
  82649. var srcData = new Float32Array(arrayBuffer, dataOffset);
  82650. var index = 0;
  82651. for (var y = 0; y < height; y++) {
  82652. for (var x = 0; x < width; x++) {
  82653. var srcPos = (x + y * width) * 4;
  82654. destArray[index] = srcData[srcPos];
  82655. destArray[index + 1] = srcData[srcPos + 1];
  82656. destArray[index + 2] = srcData[srcPos + 2];
  82657. destArray[index + 3] = lod;
  82658. index += 4;
  82659. }
  82660. }
  82661. return destArray;
  82662. }
  82663. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  82664. };
  82665. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82666. var destArray = new Uint8Array(dataLength);
  82667. var srcData = new Float32Array(arrayBuffer, dataOffset);
  82668. var index = 0;
  82669. for (var y = 0; y < height; y++) {
  82670. for (var x = 0; x < width; x++) {
  82671. var srcPos = (x + y * width) * 4;
  82672. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  82673. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  82674. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  82675. if (DDSTools.StoreLODInAlphaChannel) {
  82676. destArray[index + 3] = lod;
  82677. }
  82678. else {
  82679. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  82680. }
  82681. index += 4;
  82682. }
  82683. }
  82684. return destArray;
  82685. };
  82686. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82687. var destArray = new Uint8Array(dataLength);
  82688. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82689. var index = 0;
  82690. for (var y = 0; y < height; y++) {
  82691. for (var x = 0; x < width; x++) {
  82692. var srcPos = (x + y * width) * 4;
  82693. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  82694. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  82695. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  82696. if (DDSTools.StoreLODInAlphaChannel) {
  82697. destArray[index + 3] = lod;
  82698. }
  82699. else {
  82700. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  82701. }
  82702. index += 4;
  82703. }
  82704. }
  82705. return destArray;
  82706. };
  82707. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  82708. var byteArray = new Uint8Array(dataLength);
  82709. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82710. var index = 0;
  82711. for (var y = 0; y < height; y++) {
  82712. for (var x = 0; x < width; x++) {
  82713. var srcPos = (x + y * width) * 4;
  82714. byteArray[index] = srcData[srcPos + rOffset];
  82715. byteArray[index + 1] = srcData[srcPos + gOffset];
  82716. byteArray[index + 2] = srcData[srcPos + bOffset];
  82717. byteArray[index + 3] = srcData[srcPos + aOffset];
  82718. index += 4;
  82719. }
  82720. }
  82721. return byteArray;
  82722. };
  82723. DDSTools._ExtractLongWordOrder = function (value) {
  82724. if (value === 0 || value === 255 || value === -16777216) {
  82725. return 0;
  82726. }
  82727. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  82728. };
  82729. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  82730. var byteArray = new Uint8Array(dataLength);
  82731. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82732. var index = 0;
  82733. for (var y = 0; y < height; y++) {
  82734. for (var x = 0; x < width; x++) {
  82735. var srcPos = (x + y * width) * 3;
  82736. byteArray[index] = srcData[srcPos + rOffset];
  82737. byteArray[index + 1] = srcData[srcPos + gOffset];
  82738. byteArray[index + 2] = srcData[srcPos + bOffset];
  82739. index += 3;
  82740. }
  82741. }
  82742. return byteArray;
  82743. };
  82744. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  82745. var byteArray = new Uint8Array(dataLength);
  82746. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82747. var index = 0;
  82748. for (var y = 0; y < height; y++) {
  82749. for (var x = 0; x < width; x++) {
  82750. var srcPos = (x + y * width);
  82751. byteArray[index] = srcData[srcPos];
  82752. index++;
  82753. }
  82754. }
  82755. return byteArray;
  82756. };
  82757. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  82758. if (lodIndex === void 0) { lodIndex = -1; }
  82759. var ext = engine.getCaps().s3tc;
  82760. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  82761. var fourCC, width, height, dataLength = 0, dataOffset;
  82762. var byteArray, mipmapCount, mip;
  82763. var internalFormat = 0;
  82764. var format = 0;
  82765. var blockBytes = 1;
  82766. if (header[off_magic] !== DDS_MAGIC) {
  82767. BABYLON.Tools.Error("Invalid magic number in DDS header");
  82768. return;
  82769. }
  82770. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  82771. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  82772. return;
  82773. }
  82774. if (info.isCompressed && !ext) {
  82775. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  82776. return;
  82777. }
  82778. var bpp = header[off_RGBbpp];
  82779. dataOffset = header[off_size] + 4;
  82780. var computeFormats = false;
  82781. if (info.isFourCC) {
  82782. fourCC = header[off_pfFourCC];
  82783. switch (fourCC) {
  82784. case FOURCC_DXT1:
  82785. blockBytes = 8;
  82786. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  82787. break;
  82788. case FOURCC_DXT3:
  82789. blockBytes = 16;
  82790. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  82791. break;
  82792. case FOURCC_DXT5:
  82793. blockBytes = 16;
  82794. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  82795. break;
  82796. case FOURCC_D3DFMT_R16G16B16A16F:
  82797. computeFormats = true;
  82798. break;
  82799. case FOURCC_D3DFMT_R32G32B32A32F:
  82800. computeFormats = true;
  82801. break;
  82802. case FOURCC_DX10:
  82803. // There is an additionnal header so dataOffset need to be changed
  82804. dataOffset += 5 * 4; // 5 uints
  82805. var supported = false;
  82806. switch (info.dxgiFormat) {
  82807. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  82808. computeFormats = true;
  82809. supported = true;
  82810. break;
  82811. case DXGI_FORMAT_B8G8R8X8_UNORM:
  82812. info.isRGB = true;
  82813. info.isFourCC = false;
  82814. bpp = 32;
  82815. supported = true;
  82816. break;
  82817. }
  82818. if (supported) {
  82819. break;
  82820. }
  82821. default:
  82822. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  82823. return;
  82824. }
  82825. }
  82826. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  82827. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  82828. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  82829. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  82830. if (computeFormats) {
  82831. format = engine._getWebGLTextureType(info.textureType);
  82832. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82833. }
  82834. mipmapCount = 1;
  82835. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  82836. mipmapCount = Math.max(1, header[off_mipmapCount]);
  82837. }
  82838. for (var face = 0; face < faces; face++) {
  82839. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  82840. width = header[off_width];
  82841. height = header[off_height];
  82842. for (mip = 0; mip < mipmapCount; ++mip) {
  82843. if (lodIndex === -1 || lodIndex === mip) {
  82844. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  82845. var i = (lodIndex === -1) ? mip : 0;
  82846. if (!info.isCompressed && info.isFourCC) {
  82847. dataLength = width * height * 4;
  82848. var floatArray = null;
  82849. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  82850. if (bpp === 128) {
  82851. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82852. }
  82853. else if (bpp === 64) {
  82854. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82855. }
  82856. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82857. format = engine._getWebGLTextureType(info.textureType);
  82858. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82859. }
  82860. else {
  82861. if (bpp === 128) {
  82862. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82863. }
  82864. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  82865. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82866. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82867. format = engine._getWebGLTextureType(info.textureType);
  82868. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82869. }
  82870. else {
  82871. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82872. }
  82873. }
  82874. if (floatArray) {
  82875. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  82876. }
  82877. }
  82878. else if (info.isRGB) {
  82879. if (bpp === 24) {
  82880. dataLength = width * height * 3;
  82881. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  82882. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  82883. }
  82884. else {
  82885. dataLength = width * height * 4;
  82886. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  82887. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  82888. }
  82889. }
  82890. else if (info.isLuminance) {
  82891. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  82892. var unpaddedRowSize = width;
  82893. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  82894. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  82895. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  82896. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  82897. }
  82898. else {
  82899. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  82900. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  82901. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  82902. }
  82903. }
  82904. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  82905. width *= 0.5;
  82906. height *= 0.5;
  82907. width = Math.max(1.0, width);
  82908. height = Math.max(1.0, height);
  82909. }
  82910. if (currentFace !== undefined) {
  82911. // Loading a single face
  82912. break;
  82913. }
  82914. }
  82915. };
  82916. DDSTools.StoreLODInAlphaChannel = false;
  82917. return DDSTools;
  82918. }());
  82919. BABYLON.DDSTools = DDSTools;
  82920. })(BABYLON || (BABYLON = {}));
  82921. //# sourceMappingURL=babylon.dds.js.map
  82922. "use strict";
  82923. var BABYLON;
  82924. (function (BABYLON) {
  82925. /**
  82926. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  82927. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  82928. */
  82929. var KhronosTextureContainer = /** @class */ (function () {
  82930. /**
  82931. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  82932. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  82933. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  82934. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  82935. */
  82936. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  82937. this.arrayBuffer = arrayBuffer;
  82938. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  82939. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  82940. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  82941. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  82942. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  82943. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  82944. BABYLON.Tools.Error("texture missing KTX identifier");
  82945. return;
  82946. }
  82947. // load the reset of the header in native 32 bit int
  82948. var header = new Int32Array(this.arrayBuffer, 12, 13);
  82949. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  82950. var oppositeEndianess = header[0] === 0x01020304;
  82951. // read all the header elements in order they exist in the file, without modification (sans endainness)
  82952. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  82953. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  82954. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  82955. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  82956. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  82957. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  82958. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  82959. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  82960. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  82961. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  82962. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  82963. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  82964. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  82965. if (this.glType !== 0) {
  82966. BABYLON.Tools.Error("only compressed formats currently supported");
  82967. return;
  82968. }
  82969. else {
  82970. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  82971. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  82972. }
  82973. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  82974. BABYLON.Tools.Error("only 2D textures currently supported");
  82975. return;
  82976. }
  82977. if (this.numberOfArrayElements !== 0) {
  82978. BABYLON.Tools.Error("texture arrays not currently supported");
  82979. return;
  82980. }
  82981. if (this.numberOfFaces !== facesExpected) {
  82982. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  82983. return;
  82984. }
  82985. // we now have a completely validated file, so could use existence of loadType as success
  82986. // would need to make this more elaborate & adjust checks above to support more than one load type
  82987. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  82988. }
  82989. // not as fast hardware based, but will probably never need to use
  82990. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  82991. return ((val & 0xFF) << 24)
  82992. | ((val & 0xFF00) << 8)
  82993. | ((val >> 8) & 0xFF00)
  82994. | ((val >> 24) & 0xFF);
  82995. };
  82996. /**
  82997. * It is assumed that the texture has already been created & is currently bound
  82998. */
  82999. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  83000. switch (this.loadType) {
  83001. case KhronosTextureContainer.COMPRESSED_2D:
  83002. this._upload2DCompressedLevels(gl, loadMipmaps);
  83003. break;
  83004. case KhronosTextureContainer.TEX_2D:
  83005. case KhronosTextureContainer.COMPRESSED_3D:
  83006. case KhronosTextureContainer.TEX_3D:
  83007. }
  83008. };
  83009. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  83010. // initialize width & height for level 1
  83011. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  83012. var width = this.pixelWidth;
  83013. var height = this.pixelHeight;
  83014. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  83015. for (var level = 0; level < mipmapCount; level++) {
  83016. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  83017. for (var face = 0; face < this.numberOfFaces; face++) {
  83018. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  83019. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  83020. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  83021. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  83022. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  83023. }
  83024. width = Math.max(1.0, width * 0.5);
  83025. height = Math.max(1.0, height * 0.5);
  83026. }
  83027. };
  83028. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  83029. // load types
  83030. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  83031. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  83032. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  83033. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  83034. return KhronosTextureContainer;
  83035. }());
  83036. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  83037. })(BABYLON || (BABYLON = {}));
  83038. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  83039. "use strict";
  83040. var BABYLON;
  83041. (function (BABYLON) {
  83042. var Debug;
  83043. (function (Debug) {
  83044. /**
  83045. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  83046. */
  83047. var SkeletonViewer = /** @class */ (function () {
  83048. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  83049. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  83050. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  83051. this.skeleton = skeleton;
  83052. this.mesh = mesh;
  83053. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  83054. this.renderingGroupId = renderingGroupId;
  83055. this.color = BABYLON.Color3.White();
  83056. this._debugLines = new Array();
  83057. this._isEnabled = false;
  83058. this._scene = scene;
  83059. this.update();
  83060. this._renderFunction = this.update.bind(this);
  83061. }
  83062. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  83063. get: function () {
  83064. return this._isEnabled;
  83065. },
  83066. set: function (value) {
  83067. if (this._isEnabled === value) {
  83068. return;
  83069. }
  83070. this._isEnabled = value;
  83071. if (value) {
  83072. this._scene.registerBeforeRender(this._renderFunction);
  83073. }
  83074. else {
  83075. this._scene.unregisterBeforeRender(this._renderFunction);
  83076. }
  83077. },
  83078. enumerable: true,
  83079. configurable: true
  83080. });
  83081. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  83082. if (x === void 0) { x = 0; }
  83083. if (y === void 0) { y = 0; }
  83084. if (z === void 0) { z = 0; }
  83085. var tmat = BABYLON.Tmp.Matrix[0];
  83086. var parentBone = bone.getParent();
  83087. tmat.copyFrom(bone.getLocalMatrix());
  83088. if (x !== 0 || y !== 0 || z !== 0) {
  83089. var tmat2 = BABYLON.Tmp.Matrix[1];
  83090. BABYLON.Matrix.IdentityToRef(tmat2);
  83091. tmat2.m[12] = x;
  83092. tmat2.m[13] = y;
  83093. tmat2.m[14] = z;
  83094. tmat2.multiplyToRef(tmat, tmat);
  83095. }
  83096. if (parentBone) {
  83097. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  83098. }
  83099. tmat.multiplyToRef(meshMat, tmat);
  83100. position.x = tmat.m[12];
  83101. position.y = tmat.m[13];
  83102. position.z = tmat.m[14];
  83103. };
  83104. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  83105. var len = bones.length;
  83106. var meshPos = this.mesh.position;
  83107. for (var i = 0; i < len; i++) {
  83108. var bone = bones[i];
  83109. var points = this._debugLines[i];
  83110. if (!points) {
  83111. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83112. this._debugLines[i] = points;
  83113. }
  83114. this._getBonePosition(points[0], bone, meshMat);
  83115. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  83116. points[0].subtractInPlace(meshPos);
  83117. points[1].subtractInPlace(meshPos);
  83118. }
  83119. };
  83120. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  83121. var len = bones.length;
  83122. var boneNum = 0;
  83123. var meshPos = this.mesh.position;
  83124. for (var i = len - 1; i >= 0; i--) {
  83125. var childBone = bones[i];
  83126. var parentBone = childBone.getParent();
  83127. if (!parentBone) {
  83128. continue;
  83129. }
  83130. var points = this._debugLines[boneNum];
  83131. if (!points) {
  83132. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83133. this._debugLines[boneNum] = points;
  83134. }
  83135. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  83136. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  83137. points[0].subtractInPlace(meshPos);
  83138. points[1].subtractInPlace(meshPos);
  83139. boneNum++;
  83140. }
  83141. };
  83142. SkeletonViewer.prototype.update = function () {
  83143. if (this.autoUpdateBonesMatrices) {
  83144. this.skeleton.computeAbsoluteTransforms();
  83145. }
  83146. if (this.skeleton.bones[0].length === undefined) {
  83147. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  83148. }
  83149. else {
  83150. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  83151. }
  83152. if (!this._debugMesh) {
  83153. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  83154. this._debugMesh.renderingGroupId = this.renderingGroupId;
  83155. }
  83156. else {
  83157. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  83158. }
  83159. this._debugMesh.position.copyFrom(this.mesh.position);
  83160. this._debugMesh.color = this.color;
  83161. };
  83162. SkeletonViewer.prototype.dispose = function () {
  83163. if (this._debugMesh) {
  83164. this.isEnabled = false;
  83165. this._debugMesh.dispose();
  83166. this._debugMesh = null;
  83167. }
  83168. };
  83169. return SkeletonViewer;
  83170. }());
  83171. Debug.SkeletonViewer = SkeletonViewer;
  83172. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83173. })(BABYLON || (BABYLON = {}));
  83174. //# sourceMappingURL=babylon.skeletonViewer.js.map
  83175. "use strict";
  83176. /**
  83177. * Module Debug contains the (visual) components to debug a scene correctly
  83178. */
  83179. var BABYLON;
  83180. (function (BABYLON) {
  83181. var Debug;
  83182. (function (Debug) {
  83183. /**
  83184. * The Axes viewer will show 3 axes in a specific point in space
  83185. */
  83186. var AxesViewer = /** @class */ (function () {
  83187. function AxesViewer(scene, scaleLines) {
  83188. if (scaleLines === void 0) { scaleLines = 1; }
  83189. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83190. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83191. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83192. this.scaleLines = 1;
  83193. this.scaleLines = scaleLines;
  83194. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  83195. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  83196. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  83197. this._xmesh.renderingGroupId = 2;
  83198. this._ymesh.renderingGroupId = 2;
  83199. this._zmesh.renderingGroupId = 2;
  83200. this._xmesh.material.checkReadyOnlyOnce = true;
  83201. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  83202. this._ymesh.material.checkReadyOnlyOnce = true;
  83203. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  83204. this._zmesh.material.checkReadyOnlyOnce = true;
  83205. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  83206. this.scene = scene;
  83207. }
  83208. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  83209. var scaleLines = this.scaleLines;
  83210. if (this._xmesh) {
  83211. this._xmesh.position.copyFrom(position);
  83212. }
  83213. if (this._ymesh) {
  83214. this._ymesh.position.copyFrom(position);
  83215. }
  83216. if (this._zmesh) {
  83217. this._zmesh.position.copyFrom(position);
  83218. }
  83219. var point2 = this._xline[1];
  83220. point2.x = xaxis.x * scaleLines;
  83221. point2.y = xaxis.y * scaleLines;
  83222. point2.z = xaxis.z * scaleLines;
  83223. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  83224. point2 = this._yline[1];
  83225. point2.x = yaxis.x * scaleLines;
  83226. point2.y = yaxis.y * scaleLines;
  83227. point2.z = yaxis.z * scaleLines;
  83228. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  83229. point2 = this._zline[1];
  83230. point2.x = zaxis.x * scaleLines;
  83231. point2.y = zaxis.y * scaleLines;
  83232. point2.z = zaxis.z * scaleLines;
  83233. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  83234. };
  83235. AxesViewer.prototype.dispose = function () {
  83236. if (this._xmesh) {
  83237. this._xmesh.dispose();
  83238. }
  83239. if (this._ymesh) {
  83240. this._ymesh.dispose();
  83241. }
  83242. if (this._zmesh) {
  83243. this._zmesh.dispose();
  83244. }
  83245. this._xmesh = null;
  83246. this._ymesh = null;
  83247. this._zmesh = null;
  83248. this.scene = null;
  83249. };
  83250. return AxesViewer;
  83251. }());
  83252. Debug.AxesViewer = AxesViewer;
  83253. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83254. })(BABYLON || (BABYLON = {}));
  83255. //# sourceMappingURL=babylon.axesViewer.js.map
  83256. "use strict";
  83257. var BABYLON;
  83258. (function (BABYLON) {
  83259. var Debug;
  83260. (function (Debug) {
  83261. /**
  83262. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  83263. */
  83264. var BoneAxesViewer = /** @class */ (function (_super) {
  83265. __extends(BoneAxesViewer, _super);
  83266. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  83267. if (scaleLines === void 0) { scaleLines = 1; }
  83268. var _this = _super.call(this, scene, scaleLines) || this;
  83269. _this.pos = BABYLON.Vector3.Zero();
  83270. _this.xaxis = BABYLON.Vector3.Zero();
  83271. _this.yaxis = BABYLON.Vector3.Zero();
  83272. _this.zaxis = BABYLON.Vector3.Zero();
  83273. _this.mesh = mesh;
  83274. _this.bone = bone;
  83275. return _this;
  83276. }
  83277. BoneAxesViewer.prototype.update = function () {
  83278. if (!this.mesh || !this.bone) {
  83279. return;
  83280. }
  83281. var bone = this.bone;
  83282. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  83283. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  83284. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  83285. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  83286. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  83287. };
  83288. BoneAxesViewer.prototype.dispose = function () {
  83289. if (this.mesh) {
  83290. this.mesh = null;
  83291. this.bone = null;
  83292. _super.prototype.dispose.call(this);
  83293. }
  83294. };
  83295. return BoneAxesViewer;
  83296. }(Debug.AxesViewer));
  83297. Debug.BoneAxesViewer = BoneAxesViewer;
  83298. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83299. })(BABYLON || (BABYLON = {}));
  83300. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  83301. "use strict";
  83302. var BABYLON;
  83303. (function (BABYLON) {
  83304. var RayHelper = /** @class */ (function () {
  83305. function RayHelper(ray) {
  83306. this.ray = ray;
  83307. }
  83308. RayHelper.CreateAndShow = function (ray, scene, color) {
  83309. var helper = new RayHelper(ray);
  83310. helper.show(scene, color);
  83311. return helper;
  83312. };
  83313. RayHelper.prototype.show = function (scene, color) {
  83314. if (!this._renderFunction && this.ray) {
  83315. var ray = this.ray;
  83316. this._renderFunction = this._render.bind(this);
  83317. this._scene = scene;
  83318. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  83319. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  83320. if (this._renderFunction) {
  83321. this._scene.registerBeforeRender(this._renderFunction);
  83322. }
  83323. }
  83324. if (color && this._renderLine) {
  83325. this._renderLine.color.copyFrom(color);
  83326. }
  83327. };
  83328. RayHelper.prototype.hide = function () {
  83329. if (this._renderFunction && this._scene) {
  83330. this._scene.unregisterBeforeRender(this._renderFunction);
  83331. this._scene = null;
  83332. this._renderFunction = null;
  83333. if (this._renderLine) {
  83334. this._renderLine.dispose();
  83335. this._renderLine = null;
  83336. }
  83337. this._renderPoints = [];
  83338. }
  83339. };
  83340. RayHelper.prototype._render = function () {
  83341. var ray = this.ray;
  83342. if (!ray) {
  83343. return;
  83344. }
  83345. var point = this._renderPoints[1];
  83346. var len = Math.min(ray.length, 1000000);
  83347. point.copyFrom(ray.direction);
  83348. point.scaleInPlace(len);
  83349. point.addInPlace(ray.origin);
  83350. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  83351. };
  83352. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  83353. this._attachedToMesh = mesh;
  83354. var ray = this.ray;
  83355. if (!ray) {
  83356. return;
  83357. }
  83358. if (!ray.direction) {
  83359. ray.direction = BABYLON.Vector3.Zero();
  83360. }
  83361. if (!ray.origin) {
  83362. ray.origin = BABYLON.Vector3.Zero();
  83363. }
  83364. if (length) {
  83365. ray.length = length;
  83366. }
  83367. if (!meshSpaceOrigin) {
  83368. meshSpaceOrigin = BABYLON.Vector3.Zero();
  83369. }
  83370. if (!meshSpaceDirection) {
  83371. // -1 so that this will work with Mesh.lookAt
  83372. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  83373. }
  83374. if (!this._meshSpaceDirection) {
  83375. this._meshSpaceDirection = meshSpaceDirection.clone();
  83376. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  83377. }
  83378. else {
  83379. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  83380. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  83381. }
  83382. if (!this._updateToMeshFunction) {
  83383. this._updateToMeshFunction = this._updateToMesh.bind(this);
  83384. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  83385. }
  83386. this._updateToMesh();
  83387. };
  83388. RayHelper.prototype.detachFromMesh = function () {
  83389. if (this._attachedToMesh) {
  83390. if (this._updateToMeshFunction) {
  83391. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  83392. }
  83393. this._attachedToMesh = null;
  83394. this._updateToMeshFunction = null;
  83395. }
  83396. };
  83397. RayHelper.prototype._updateToMesh = function () {
  83398. var ray = this.ray;
  83399. if (!this._attachedToMesh || !ray) {
  83400. return;
  83401. }
  83402. if (this._attachedToMesh._isDisposed) {
  83403. this.detachFromMesh();
  83404. return;
  83405. }
  83406. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  83407. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  83408. };
  83409. RayHelper.prototype.dispose = function () {
  83410. this.hide();
  83411. this.detachFromMesh();
  83412. this.ray = null;
  83413. };
  83414. return RayHelper;
  83415. }());
  83416. BABYLON.RayHelper = RayHelper;
  83417. })(BABYLON || (BABYLON = {}));
  83418. //# sourceMappingURL=babylon.rayHelper.js.map
  83419. "use strict";
  83420. var BABYLON;
  83421. (function (BABYLON) {
  83422. // load the inspector using require, if not present in the global namespace.
  83423. var DebugLayer = /** @class */ (function () {
  83424. function DebugLayer(scene) {
  83425. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  83426. this._scene = scene;
  83427. // load inspector using require, if it doesn't exist on the global namespace.
  83428. }
  83429. /** Creates the inspector window. */
  83430. DebugLayer.prototype._createInspector = function (config) {
  83431. if (config === void 0) { config = {}; }
  83432. var popup = config.popup || false;
  83433. var initialTab = config.initialTab || 0;
  83434. var parentElement = config.parentElement || null;
  83435. if (!this._inspector) {
  83436. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  83437. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  83438. } // else nothing to do,; instance is already existing
  83439. };
  83440. DebugLayer.prototype.isVisible = function () {
  83441. if (!this._inspector) {
  83442. return false;
  83443. }
  83444. return true;
  83445. };
  83446. DebugLayer.prototype.hide = function () {
  83447. if (this._inspector) {
  83448. try {
  83449. this._inspector.dispose();
  83450. }
  83451. catch (e) {
  83452. // If the inspector has been removed directly from the inspector tool
  83453. }
  83454. this._inspector = null;
  83455. }
  83456. };
  83457. DebugLayer.prototype.show = function (config) {
  83458. if (config === void 0) { config = {}; }
  83459. if (typeof this.BJSINSPECTOR == 'undefined') {
  83460. // Load inspector and add it to the DOM
  83461. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  83462. }
  83463. else {
  83464. // Otherwise creates the inspector
  83465. this._createInspector(config);
  83466. }
  83467. };
  83468. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  83469. return DebugLayer;
  83470. }());
  83471. BABYLON.DebugLayer = DebugLayer;
  83472. })(BABYLON || (BABYLON = {}));
  83473. //# sourceMappingURL=babylon.debugLayer.js.map
  83474. "use strict";
  83475. var BABYLON;
  83476. (function (BABYLON) {
  83477. var Debug;
  83478. (function (Debug) {
  83479. /**
  83480. * Used to show the physics impostor around the specific mesh.
  83481. */
  83482. var PhysicsViewer = /** @class */ (function () {
  83483. function PhysicsViewer(scene) {
  83484. this._impostors = [];
  83485. this._meshes = [];
  83486. this._numMeshes = 0;
  83487. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83488. var physicEngine = this._scene.getPhysicsEngine();
  83489. if (physicEngine) {
  83490. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  83491. }
  83492. }
  83493. PhysicsViewer.prototype._updateDebugMeshes = function () {
  83494. var plugin = this._physicsEnginePlugin;
  83495. for (var i = 0; i < this._numMeshes; i++) {
  83496. var impostor = this._impostors[i];
  83497. if (!impostor) {
  83498. continue;
  83499. }
  83500. if (impostor.isDisposed) {
  83501. this.hideImpostor(this._impostors[i--]);
  83502. }
  83503. else {
  83504. var mesh = this._meshes[i];
  83505. if (mesh && plugin) {
  83506. plugin.syncMeshWithImpostor(mesh, impostor);
  83507. }
  83508. }
  83509. }
  83510. };
  83511. PhysicsViewer.prototype.showImpostor = function (impostor) {
  83512. if (!this._scene) {
  83513. return;
  83514. }
  83515. for (var i = 0; i < this._numMeshes; i++) {
  83516. if (this._impostors[i] == impostor) {
  83517. return;
  83518. }
  83519. }
  83520. var debugMesh = this._getDebugMesh(impostor, this._scene);
  83521. if (debugMesh) {
  83522. this._impostors[this._numMeshes] = impostor;
  83523. this._meshes[this._numMeshes] = debugMesh;
  83524. if (this._numMeshes === 0) {
  83525. this._renderFunction = this._updateDebugMeshes.bind(this);
  83526. this._scene.registerBeforeRender(this._renderFunction);
  83527. }
  83528. this._numMeshes++;
  83529. }
  83530. };
  83531. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  83532. if (!impostor || !this._scene) {
  83533. return;
  83534. }
  83535. var removed = false;
  83536. for (var i = 0; i < this._numMeshes; i++) {
  83537. if (this._impostors[i] == impostor) {
  83538. var mesh = this._meshes[i];
  83539. if (!mesh) {
  83540. continue;
  83541. }
  83542. this._scene.removeMesh(mesh);
  83543. mesh.dispose();
  83544. this._numMeshes--;
  83545. if (this._numMeshes > 0) {
  83546. this._meshes[i] = this._meshes[this._numMeshes];
  83547. this._impostors[i] = this._impostors[this._numMeshes];
  83548. this._meshes[this._numMeshes] = null;
  83549. this._impostors[this._numMeshes] = null;
  83550. }
  83551. else {
  83552. this._meshes[0] = null;
  83553. this._impostors[0] = null;
  83554. }
  83555. removed = true;
  83556. break;
  83557. }
  83558. }
  83559. if (removed && this._numMeshes === 0) {
  83560. this._scene.unregisterBeforeRender(this._renderFunction);
  83561. }
  83562. };
  83563. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  83564. if (!this._debugMaterial) {
  83565. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  83566. this._debugMaterial.wireframe = true;
  83567. }
  83568. return this._debugMaterial;
  83569. };
  83570. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  83571. if (!this._debugBoxMesh) {
  83572. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  83573. this._debugBoxMesh.renderingGroupId = 1;
  83574. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83575. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  83576. scene.removeMesh(this._debugBoxMesh);
  83577. }
  83578. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  83579. };
  83580. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  83581. if (!this._debugSphereMesh) {
  83582. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  83583. this._debugSphereMesh.renderingGroupId = 1;
  83584. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83585. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  83586. scene.removeMesh(this._debugSphereMesh);
  83587. }
  83588. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  83589. };
  83590. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  83591. var mesh = null;
  83592. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  83593. mesh = this._getDebugBoxMesh(scene);
  83594. impostor.getBoxSizeToRef(mesh.scaling);
  83595. }
  83596. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  83597. mesh = this._getDebugSphereMesh(scene);
  83598. var radius = impostor.getRadius();
  83599. mesh.scaling.x = radius * 2;
  83600. mesh.scaling.y = radius * 2;
  83601. mesh.scaling.z = radius * 2;
  83602. }
  83603. return mesh;
  83604. };
  83605. PhysicsViewer.prototype.dispose = function () {
  83606. for (var i = 0; i < this._numMeshes; i++) {
  83607. this.hideImpostor(this._impostors[i]);
  83608. }
  83609. if (this._debugBoxMesh) {
  83610. this._debugBoxMesh.dispose();
  83611. }
  83612. if (this._debugSphereMesh) {
  83613. this._debugSphereMesh.dispose();
  83614. }
  83615. if (this._debugMaterial) {
  83616. this._debugMaterial.dispose();
  83617. }
  83618. this._impostors.length = 0;
  83619. this._scene = null;
  83620. this._physicsEnginePlugin = null;
  83621. };
  83622. return PhysicsViewer;
  83623. }());
  83624. Debug.PhysicsViewer = PhysicsViewer;
  83625. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83626. })(BABYLON || (BABYLON = {}));
  83627. //# sourceMappingURL=babylon.physicsViewer.js.map
  83628. "use strict";
  83629. var BABYLON;
  83630. (function (BABYLON) {
  83631. var BoundingBoxRenderer = /** @class */ (function () {
  83632. function BoundingBoxRenderer(scene) {
  83633. this.frontColor = new BABYLON.Color3(1, 1, 1);
  83634. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  83635. this.showBackLines = true;
  83636. this.renderList = new BABYLON.SmartArray(32);
  83637. this._vertexBuffers = {};
  83638. this._scene = scene;
  83639. }
  83640. BoundingBoxRenderer.prototype._prepareRessources = function () {
  83641. if (this._colorShader) {
  83642. return;
  83643. }
  83644. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  83645. attributes: [BABYLON.VertexBuffer.PositionKind],
  83646. uniforms: ["world", "viewProjection", "color"]
  83647. });
  83648. var engine = this._scene.getEngine();
  83649. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  83650. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  83651. this._createIndexBuffer();
  83652. };
  83653. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  83654. var engine = this._scene.getEngine();
  83655. 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]);
  83656. };
  83657. BoundingBoxRenderer.prototype._rebuild = function () {
  83658. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83659. if (vb) {
  83660. vb._rebuild();
  83661. }
  83662. this._createIndexBuffer();
  83663. };
  83664. BoundingBoxRenderer.prototype.reset = function () {
  83665. this.renderList.reset();
  83666. };
  83667. BoundingBoxRenderer.prototype.render = function () {
  83668. if (this.renderList.length === 0) {
  83669. return;
  83670. }
  83671. this._prepareRessources();
  83672. if (!this._colorShader.isReady()) {
  83673. return;
  83674. }
  83675. var engine = this._scene.getEngine();
  83676. engine.setDepthWrite(false);
  83677. this._colorShader._preBind();
  83678. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  83679. var boundingBox = this.renderList.data[boundingBoxIndex];
  83680. var min = boundingBox.minimum;
  83681. var max = boundingBox.maximum;
  83682. var diff = max.subtract(min);
  83683. var median = min.add(diff.scale(0.5));
  83684. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  83685. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  83686. .multiply(boundingBox.getWorldMatrix());
  83687. // VBOs
  83688. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  83689. if (this.showBackLines) {
  83690. // Back
  83691. engine.setDepthFunctionToGreaterOrEqual();
  83692. this._scene.resetCachedMaterial();
  83693. this._colorShader.setColor4("color", this.backColor.toColor4());
  83694. this._colorShader.bind(worldMatrix);
  83695. // Draw order
  83696. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83697. }
  83698. // Front
  83699. engine.setDepthFunctionToLess();
  83700. this._scene.resetCachedMaterial();
  83701. this._colorShader.setColor4("color", this.frontColor.toColor4());
  83702. this._colorShader.bind(worldMatrix);
  83703. // Draw order
  83704. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83705. }
  83706. this._colorShader.unbind();
  83707. engine.setDepthFunctionToLessOrEqual();
  83708. engine.setDepthWrite(true);
  83709. };
  83710. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  83711. this._prepareRessources();
  83712. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  83713. return;
  83714. }
  83715. var engine = this._scene.getEngine();
  83716. engine.setDepthWrite(false);
  83717. engine.setColorWrite(false);
  83718. this._colorShader._preBind();
  83719. var boundingBox = mesh._boundingInfo.boundingBox;
  83720. var min = boundingBox.minimum;
  83721. var max = boundingBox.maximum;
  83722. var diff = max.subtract(min);
  83723. var median = min.add(diff.scale(0.5));
  83724. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  83725. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  83726. .multiply(boundingBox.getWorldMatrix());
  83727. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  83728. engine.setDepthFunctionToLess();
  83729. this._scene.resetCachedMaterial();
  83730. this._colorShader.bind(worldMatrix);
  83731. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83732. this._colorShader.unbind();
  83733. engine.setDepthFunctionToLessOrEqual();
  83734. engine.setDepthWrite(true);
  83735. engine.setColorWrite(true);
  83736. };
  83737. BoundingBoxRenderer.prototype.dispose = function () {
  83738. if (!this._colorShader) {
  83739. return;
  83740. }
  83741. this.renderList.dispose();
  83742. this._colorShader.dispose();
  83743. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83744. if (buffer) {
  83745. buffer.dispose();
  83746. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83747. }
  83748. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83749. };
  83750. return BoundingBoxRenderer;
  83751. }());
  83752. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  83753. })(BABYLON || (BABYLON = {}));
  83754. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  83755. "use strict";
  83756. var BABYLON;
  83757. (function (BABYLON) {
  83758. var MorphTarget = /** @class */ (function () {
  83759. function MorphTarget(name, influence) {
  83760. if (influence === void 0) { influence = 0; }
  83761. this.name = name;
  83762. this.animations = new Array();
  83763. this._positions = null;
  83764. this._normals = null;
  83765. this._tangents = null;
  83766. this.onInfluenceChanged = new BABYLON.Observable();
  83767. this.influence = influence;
  83768. }
  83769. Object.defineProperty(MorphTarget.prototype, "influence", {
  83770. get: function () {
  83771. return this._influence;
  83772. },
  83773. set: function (influence) {
  83774. if (this._influence === influence) {
  83775. return;
  83776. }
  83777. var previous = this._influence;
  83778. this._influence = influence;
  83779. if (this.onInfluenceChanged.hasObservers) {
  83780. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  83781. }
  83782. },
  83783. enumerable: true,
  83784. configurable: true
  83785. });
  83786. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  83787. get: function () {
  83788. return !!this._positions;
  83789. },
  83790. enumerable: true,
  83791. configurable: true
  83792. });
  83793. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  83794. get: function () {
  83795. return !!this._normals;
  83796. },
  83797. enumerable: true,
  83798. configurable: true
  83799. });
  83800. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  83801. get: function () {
  83802. return !!this._tangents;
  83803. },
  83804. enumerable: true,
  83805. configurable: true
  83806. });
  83807. MorphTarget.prototype.setPositions = function (data) {
  83808. this._positions = data;
  83809. };
  83810. MorphTarget.prototype.getPositions = function () {
  83811. return this._positions;
  83812. };
  83813. MorphTarget.prototype.setNormals = function (data) {
  83814. this._normals = data;
  83815. };
  83816. MorphTarget.prototype.getNormals = function () {
  83817. return this._normals;
  83818. };
  83819. MorphTarget.prototype.setTangents = function (data) {
  83820. this._tangents = data;
  83821. };
  83822. MorphTarget.prototype.getTangents = function () {
  83823. return this._tangents;
  83824. };
  83825. /**
  83826. * Serializes the current target into a Serialization object.
  83827. * Returns the serialized object.
  83828. */
  83829. MorphTarget.prototype.serialize = function () {
  83830. var serializationObject = {};
  83831. serializationObject.name = this.name;
  83832. serializationObject.influence = this.influence;
  83833. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  83834. if (this.hasNormals) {
  83835. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  83836. }
  83837. if (this.hasTangents) {
  83838. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  83839. }
  83840. // Animations
  83841. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  83842. return serializationObject;
  83843. };
  83844. // Statics
  83845. MorphTarget.Parse = function (serializationObject) {
  83846. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  83847. result.setPositions(serializationObject.positions);
  83848. if (serializationObject.normals) {
  83849. result.setNormals(serializationObject.normals);
  83850. }
  83851. if (serializationObject.tangents) {
  83852. result.setTangents(serializationObject.tangents);
  83853. }
  83854. // Animations
  83855. if (serializationObject.animations) {
  83856. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  83857. var parsedAnimation = serializationObject.animations[animationIndex];
  83858. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  83859. }
  83860. }
  83861. return result;
  83862. };
  83863. MorphTarget.FromMesh = function (mesh, name, influence) {
  83864. if (!name) {
  83865. name = mesh.name;
  83866. }
  83867. var result = new MorphTarget(name, influence);
  83868. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83869. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  83870. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  83871. }
  83872. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  83873. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  83874. }
  83875. return result;
  83876. };
  83877. return MorphTarget;
  83878. }());
  83879. BABYLON.MorphTarget = MorphTarget;
  83880. })(BABYLON || (BABYLON = {}));
  83881. //# sourceMappingURL=babylon.morphTarget.js.map
  83882. "use strict";
  83883. var BABYLON;
  83884. (function (BABYLON) {
  83885. var MorphTargetManager = /** @class */ (function () {
  83886. function MorphTargetManager(scene) {
  83887. if (scene === void 0) { scene = null; }
  83888. this._targets = new Array();
  83889. this._targetObservable = new Array();
  83890. this._activeTargets = new BABYLON.SmartArray(16);
  83891. this._supportsNormals = false;
  83892. this._supportsTangents = false;
  83893. this._vertexCount = 0;
  83894. this._uniqueId = 0;
  83895. this._tempInfluences = new Array();
  83896. if (!scene) {
  83897. scene = BABYLON.Engine.LastCreatedScene;
  83898. }
  83899. this._scene = scene;
  83900. if (this._scene) {
  83901. this._scene.morphTargetManagers.push(this);
  83902. this._uniqueId = this._scene.getUniqueId();
  83903. }
  83904. }
  83905. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  83906. get: function () {
  83907. return this._uniqueId;
  83908. },
  83909. enumerable: true,
  83910. configurable: true
  83911. });
  83912. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  83913. get: function () {
  83914. return this._vertexCount;
  83915. },
  83916. enumerable: true,
  83917. configurable: true
  83918. });
  83919. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  83920. get: function () {
  83921. return this._supportsNormals;
  83922. },
  83923. enumerable: true,
  83924. configurable: true
  83925. });
  83926. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  83927. get: function () {
  83928. return this._supportsTangents;
  83929. },
  83930. enumerable: true,
  83931. configurable: true
  83932. });
  83933. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  83934. get: function () {
  83935. return this._targets.length;
  83936. },
  83937. enumerable: true,
  83938. configurable: true
  83939. });
  83940. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  83941. get: function () {
  83942. return this._activeTargets.length;
  83943. },
  83944. enumerable: true,
  83945. configurable: true
  83946. });
  83947. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  83948. get: function () {
  83949. return this._influences;
  83950. },
  83951. enumerable: true,
  83952. configurable: true
  83953. });
  83954. MorphTargetManager.prototype.getActiveTarget = function (index) {
  83955. return this._activeTargets.data[index];
  83956. };
  83957. MorphTargetManager.prototype.getTarget = function (index) {
  83958. return this._targets[index];
  83959. };
  83960. MorphTargetManager.prototype.addTarget = function (target) {
  83961. var _this = this;
  83962. this._targets.push(target);
  83963. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  83964. _this._syncActiveTargets(needUpdate);
  83965. }));
  83966. this._syncActiveTargets(true);
  83967. };
  83968. MorphTargetManager.prototype.removeTarget = function (target) {
  83969. var index = this._targets.indexOf(target);
  83970. if (index >= 0) {
  83971. this._targets.splice(index, 1);
  83972. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  83973. this._syncActiveTargets(true);
  83974. }
  83975. };
  83976. /**
  83977. * Serializes the current manager into a Serialization object.
  83978. * Returns the serialized object.
  83979. */
  83980. MorphTargetManager.prototype.serialize = function () {
  83981. var serializationObject = {};
  83982. serializationObject.id = this.uniqueId;
  83983. serializationObject.targets = [];
  83984. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  83985. var target = _a[_i];
  83986. serializationObject.targets.push(target.serialize());
  83987. }
  83988. return serializationObject;
  83989. };
  83990. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  83991. var influenceCount = 0;
  83992. this._activeTargets.reset();
  83993. this._supportsNormals = true;
  83994. this._supportsTangents = true;
  83995. this._vertexCount = 0;
  83996. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  83997. var target = _a[_i];
  83998. this._activeTargets.push(target);
  83999. this._tempInfluences[influenceCount++] = target.influence;
  84000. var positions = target.getPositions();
  84001. if (positions) {
  84002. this._supportsNormals = this._supportsNormals && target.hasNormals;
  84003. this._supportsTangents = this._supportsTangents && target.hasTangents;
  84004. var vertexCount = positions.length / 3;
  84005. if (this._vertexCount === 0) {
  84006. this._vertexCount = vertexCount;
  84007. }
  84008. else if (this._vertexCount !== vertexCount) {
  84009. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  84010. return;
  84011. }
  84012. }
  84013. }
  84014. if (!this._influences || this._influences.length !== influenceCount) {
  84015. this._influences = new Float32Array(influenceCount);
  84016. }
  84017. for (var index = 0; index < influenceCount; index++) {
  84018. this._influences[index] = this._tempInfluences[index];
  84019. }
  84020. if (needUpdate && this._scene) {
  84021. // Flag meshes as dirty to resync with the active targets
  84022. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  84023. var mesh = _c[_b];
  84024. if (mesh.morphTargetManager === this) {
  84025. mesh._syncGeometryWithMorphTargetManager();
  84026. }
  84027. }
  84028. }
  84029. };
  84030. // Statics
  84031. MorphTargetManager.Parse = function (serializationObject, scene) {
  84032. var result = new MorphTargetManager(scene);
  84033. result._uniqueId = serializationObject.id;
  84034. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  84035. var targetData = _a[_i];
  84036. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  84037. }
  84038. return result;
  84039. };
  84040. return MorphTargetManager;
  84041. }());
  84042. BABYLON.MorphTargetManager = MorphTargetManager;
  84043. })(BABYLON || (BABYLON = {}));
  84044. //# sourceMappingURL=babylon.morphTargetManager.js.map
  84045. "use strict";
  84046. var BABYLON;
  84047. (function (BABYLON) {
  84048. var Octree = /** @class */ (function () {
  84049. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  84050. if (maxDepth === void 0) { maxDepth = 2; }
  84051. this.maxDepth = maxDepth;
  84052. this.dynamicContent = new Array();
  84053. this._maxBlockCapacity = maxBlockCapacity || 64;
  84054. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  84055. this._creationFunc = creationFunc;
  84056. }
  84057. // Methods
  84058. Octree.prototype.update = function (worldMin, worldMax, entries) {
  84059. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  84060. };
  84061. Octree.prototype.addMesh = function (entry) {
  84062. for (var index = 0; index < this.blocks.length; index++) {
  84063. var block = this.blocks[index];
  84064. block.addEntry(entry);
  84065. }
  84066. };
  84067. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  84068. this._selectionContent.reset();
  84069. for (var index = 0; index < this.blocks.length; index++) {
  84070. var block = this.blocks[index];
  84071. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  84072. }
  84073. if (allowDuplicate) {
  84074. this._selectionContent.concat(this.dynamicContent);
  84075. }
  84076. else {
  84077. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84078. }
  84079. return this._selectionContent;
  84080. };
  84081. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  84082. this._selectionContent.reset();
  84083. for (var index = 0; index < this.blocks.length; index++) {
  84084. var block = this.blocks[index];
  84085. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  84086. }
  84087. if (allowDuplicate) {
  84088. this._selectionContent.concat(this.dynamicContent);
  84089. }
  84090. else {
  84091. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84092. }
  84093. return this._selectionContent;
  84094. };
  84095. Octree.prototype.intersectsRay = function (ray) {
  84096. this._selectionContent.reset();
  84097. for (var index = 0; index < this.blocks.length; index++) {
  84098. var block = this.blocks[index];
  84099. block.intersectsRay(ray, this._selectionContent);
  84100. }
  84101. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84102. return this._selectionContent;
  84103. };
  84104. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  84105. target.blocks = new Array();
  84106. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  84107. // Segmenting space
  84108. for (var x = 0; x < 2; x++) {
  84109. for (var y = 0; y < 2; y++) {
  84110. for (var z = 0; z < 2; z++) {
  84111. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  84112. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  84113. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  84114. block.addEntries(entries);
  84115. target.blocks.push(block);
  84116. }
  84117. }
  84118. }
  84119. };
  84120. Octree.CreationFuncForMeshes = function (entry, block) {
  84121. var boundingInfo = entry.getBoundingInfo();
  84122. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  84123. block.entries.push(entry);
  84124. }
  84125. };
  84126. Octree.CreationFuncForSubMeshes = function (entry, block) {
  84127. var boundingInfo = entry.getBoundingInfo();
  84128. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  84129. block.entries.push(entry);
  84130. }
  84131. };
  84132. return Octree;
  84133. }());
  84134. BABYLON.Octree = Octree;
  84135. })(BABYLON || (BABYLON = {}));
  84136. //# sourceMappingURL=babylon.octree.js.map
  84137. "use strict";
  84138. var BABYLON;
  84139. (function (BABYLON) {
  84140. var OctreeBlock = /** @class */ (function () {
  84141. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  84142. this.entries = new Array();
  84143. this._boundingVectors = new Array();
  84144. this._capacity = capacity;
  84145. this._depth = depth;
  84146. this._maxDepth = maxDepth;
  84147. this._creationFunc = creationFunc;
  84148. this._minPoint = minPoint;
  84149. this._maxPoint = maxPoint;
  84150. this._boundingVectors.push(minPoint.clone());
  84151. this._boundingVectors.push(maxPoint.clone());
  84152. this._boundingVectors.push(minPoint.clone());
  84153. this._boundingVectors[2].x = maxPoint.x;
  84154. this._boundingVectors.push(minPoint.clone());
  84155. this._boundingVectors[3].y = maxPoint.y;
  84156. this._boundingVectors.push(minPoint.clone());
  84157. this._boundingVectors[4].z = maxPoint.z;
  84158. this._boundingVectors.push(maxPoint.clone());
  84159. this._boundingVectors[5].z = minPoint.z;
  84160. this._boundingVectors.push(maxPoint.clone());
  84161. this._boundingVectors[6].x = minPoint.x;
  84162. this._boundingVectors.push(maxPoint.clone());
  84163. this._boundingVectors[7].y = minPoint.y;
  84164. }
  84165. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  84166. // Property
  84167. get: function () {
  84168. return this._capacity;
  84169. },
  84170. enumerable: true,
  84171. configurable: true
  84172. });
  84173. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  84174. get: function () {
  84175. return this._minPoint;
  84176. },
  84177. enumerable: true,
  84178. configurable: true
  84179. });
  84180. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  84181. get: function () {
  84182. return this._maxPoint;
  84183. },
  84184. enumerable: true,
  84185. configurable: true
  84186. });
  84187. // Methods
  84188. OctreeBlock.prototype.addEntry = function (entry) {
  84189. if (this.blocks) {
  84190. for (var index = 0; index < this.blocks.length; index++) {
  84191. var block = this.blocks[index];
  84192. block.addEntry(entry);
  84193. }
  84194. return;
  84195. }
  84196. this._creationFunc(entry, this);
  84197. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  84198. this.createInnerBlocks();
  84199. }
  84200. };
  84201. OctreeBlock.prototype.addEntries = function (entries) {
  84202. for (var index = 0; index < entries.length; index++) {
  84203. var mesh = entries[index];
  84204. this.addEntry(mesh);
  84205. }
  84206. };
  84207. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  84208. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  84209. if (this.blocks) {
  84210. for (var index = 0; index < this.blocks.length; index++) {
  84211. var block = this.blocks[index];
  84212. block.select(frustumPlanes, selection, allowDuplicate);
  84213. }
  84214. return;
  84215. }
  84216. if (allowDuplicate) {
  84217. selection.concat(this.entries);
  84218. }
  84219. else {
  84220. selection.concatWithNoDuplicate(this.entries);
  84221. }
  84222. }
  84223. };
  84224. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  84225. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  84226. if (this.blocks) {
  84227. for (var index = 0; index < this.blocks.length; index++) {
  84228. var block = this.blocks[index];
  84229. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  84230. }
  84231. return;
  84232. }
  84233. if (allowDuplicate) {
  84234. selection.concat(this.entries);
  84235. }
  84236. else {
  84237. selection.concatWithNoDuplicate(this.entries);
  84238. }
  84239. }
  84240. };
  84241. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  84242. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  84243. if (this.blocks) {
  84244. for (var index = 0; index < this.blocks.length; index++) {
  84245. var block = this.blocks[index];
  84246. block.intersectsRay(ray, selection);
  84247. }
  84248. return;
  84249. }
  84250. selection.concatWithNoDuplicate(this.entries);
  84251. }
  84252. };
  84253. OctreeBlock.prototype.createInnerBlocks = function () {
  84254. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  84255. };
  84256. return OctreeBlock;
  84257. }());
  84258. BABYLON.OctreeBlock = OctreeBlock;
  84259. })(BABYLON || (BABYLON = {}));
  84260. //# sourceMappingURL=babylon.octreeBlock.js.map
  84261. "use strict";
  84262. var BABYLON;
  84263. (function (BABYLON) {
  84264. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  84265. __extends(VRDistortionCorrectionPostProcess, _super);
  84266. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  84267. var _this = _super.call(this, name, "vrDistortionCorrection", [
  84268. 'LensCenter',
  84269. 'Scale',
  84270. 'ScaleIn',
  84271. 'HmdWarpParam'
  84272. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  84273. _this._isRightEye = isRightEye;
  84274. _this._distortionFactors = vrMetrics.distortionK;
  84275. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  84276. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  84277. _this.adaptScaleToCurrentViewport = true;
  84278. _this.onSizeChangedObservable.add(function () {
  84279. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  84280. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  84281. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  84282. });
  84283. _this.onApplyObservable.add(function (effect) {
  84284. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  84285. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  84286. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  84287. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  84288. });
  84289. return _this;
  84290. }
  84291. return VRDistortionCorrectionPostProcess;
  84292. }(BABYLON.PostProcess));
  84293. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  84294. })(BABYLON || (BABYLON = {}));
  84295. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  84296. "use strict";
  84297. var BABYLON;
  84298. (function (BABYLON) {
  84299. var AnaglyphPostProcess = /** @class */ (function (_super) {
  84300. __extends(AnaglyphPostProcess, _super);
  84301. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  84302. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  84303. _this._passedProcess = rigCameras[0]._rigPostProcess;
  84304. _this.onApplyObservable.add(function (effect) {
  84305. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  84306. });
  84307. return _this;
  84308. }
  84309. return AnaglyphPostProcess;
  84310. }(BABYLON.PostProcess));
  84311. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  84312. })(BABYLON || (BABYLON = {}));
  84313. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  84314. "use strict";
  84315. var BABYLON;
  84316. (function (BABYLON) {
  84317. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  84318. __extends(StereoscopicInterlacePostProcess, _super);
  84319. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  84320. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  84321. _this._passedProcess = rigCameras[0]._rigPostProcess;
  84322. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  84323. _this.onSizeChangedObservable.add(function () {
  84324. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  84325. });
  84326. _this.onApplyObservable.add(function (effect) {
  84327. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  84328. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  84329. });
  84330. return _this;
  84331. }
  84332. return StereoscopicInterlacePostProcess;
  84333. }(BABYLON.PostProcess));
  84334. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  84335. })(BABYLON || (BABYLON = {}));
  84336. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  84337. "use strict";
  84338. var BABYLON;
  84339. (function (BABYLON) {
  84340. /**
  84341. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  84342. * Screen rotation is taken into account.
  84343. */
  84344. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  84345. function FreeCameraDeviceOrientationInput() {
  84346. var _this = this;
  84347. this._screenOrientationAngle = 0;
  84348. this._screenQuaternion = new BABYLON.Quaternion();
  84349. this._alpha = 0;
  84350. this._beta = 0;
  84351. this._gamma = 0;
  84352. this._orientationChanged = function () {
  84353. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  84354. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  84355. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  84356. };
  84357. this._deviceOrientation = function (evt) {
  84358. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  84359. _this._beta = evt.beta !== null ? evt.beta : 0;
  84360. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  84361. };
  84362. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  84363. this._orientationChanged();
  84364. }
  84365. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  84366. get: function () {
  84367. return this._camera;
  84368. },
  84369. set: function (camera) {
  84370. this._camera = camera;
  84371. if (this._camera != null && !this._camera.rotationQuaternion) {
  84372. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  84373. }
  84374. },
  84375. enumerable: true,
  84376. configurable: true
  84377. });
  84378. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  84379. window.addEventListener("orientationchange", this._orientationChanged);
  84380. window.addEventListener("deviceorientation", this._deviceOrientation);
  84381. //In certain cases, the attach control is called AFTER orientation was changed,
  84382. //So this is needed.
  84383. this._orientationChanged();
  84384. };
  84385. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  84386. window.removeEventListener("orientationchange", this._orientationChanged);
  84387. window.removeEventListener("deviceorientation", this._deviceOrientation);
  84388. };
  84389. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  84390. //if no device orientation provided, don't update the rotation.
  84391. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  84392. if (!this._alpha)
  84393. return;
  84394. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  84395. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  84396. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  84397. //Mirror on XY Plane
  84398. this._camera.rotationQuaternion.z *= -1;
  84399. this._camera.rotationQuaternion.w *= -1;
  84400. };
  84401. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  84402. return "FreeCameraDeviceOrientationInput";
  84403. };
  84404. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  84405. return "deviceOrientation";
  84406. };
  84407. return FreeCameraDeviceOrientationInput;
  84408. }());
  84409. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  84410. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  84411. })(BABYLON || (BABYLON = {}));
  84412. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  84413. "use strict";
  84414. var BABYLON;
  84415. (function (BABYLON) {
  84416. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  84417. function ArcRotateCameraVRDeviceOrientationInput() {
  84418. this.alphaCorrection = 1;
  84419. this.betaCorrection = 1;
  84420. this.gammaCorrection = 1;
  84421. this._alpha = 0;
  84422. this._gamma = 0;
  84423. this._dirty = false;
  84424. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  84425. }
  84426. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  84427. this.camera.attachControl(element, noPreventDefault);
  84428. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  84429. };
  84430. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  84431. if (evt.alpha !== null) {
  84432. this._alpha = +evt.alpha | 0;
  84433. }
  84434. if (evt.gamma !== null) {
  84435. this._gamma = +evt.gamma | 0;
  84436. }
  84437. this._dirty = true;
  84438. };
  84439. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  84440. if (this._dirty) {
  84441. this._dirty = false;
  84442. if (this._gamma < 0) {
  84443. this._gamma = 180 + this._gamma;
  84444. }
  84445. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  84446. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  84447. }
  84448. };
  84449. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  84450. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  84451. };
  84452. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  84453. return "ArcRotateCameraVRDeviceOrientationInput";
  84454. };
  84455. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  84456. return "VRDeviceOrientation";
  84457. };
  84458. return ArcRotateCameraVRDeviceOrientationInput;
  84459. }());
  84460. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  84461. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  84462. })(BABYLON || (BABYLON = {}));
  84463. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  84464. "use strict";
  84465. var BABYLON;
  84466. (function (BABYLON) {
  84467. var VRCameraMetrics = /** @class */ (function () {
  84468. function VRCameraMetrics() {
  84469. this.compensateDistortion = true;
  84470. }
  84471. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  84472. get: function () {
  84473. return this.hResolution / (2 * this.vResolution);
  84474. },
  84475. enumerable: true,
  84476. configurable: true
  84477. });
  84478. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  84479. get: function () {
  84480. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  84481. },
  84482. enumerable: true,
  84483. configurable: true
  84484. });
  84485. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  84486. get: function () {
  84487. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  84488. var h = (4 * meters) / this.hScreenSize;
  84489. return BABYLON.Matrix.Translation(h, 0, 0);
  84490. },
  84491. enumerable: true,
  84492. configurable: true
  84493. });
  84494. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  84495. get: function () {
  84496. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  84497. var h = (4 * meters) / this.hScreenSize;
  84498. return BABYLON.Matrix.Translation(-h, 0, 0);
  84499. },
  84500. enumerable: true,
  84501. configurable: true
  84502. });
  84503. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  84504. get: function () {
  84505. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  84506. },
  84507. enumerable: true,
  84508. configurable: true
  84509. });
  84510. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  84511. get: function () {
  84512. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  84513. },
  84514. enumerable: true,
  84515. configurable: true
  84516. });
  84517. VRCameraMetrics.GetDefault = function () {
  84518. var result = new VRCameraMetrics();
  84519. result.hResolution = 1280;
  84520. result.vResolution = 800;
  84521. result.hScreenSize = 0.149759993;
  84522. result.vScreenSize = 0.0935999975;
  84523. result.vScreenCenter = 0.0467999987;
  84524. result.eyeToScreenDistance = 0.0410000011;
  84525. result.lensSeparationDistance = 0.0635000020;
  84526. result.interpupillaryDistance = 0.0640000030;
  84527. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  84528. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  84529. result.postProcessScaleFactor = 1.714605507808412;
  84530. result.lensCenterOffset = 0.151976421;
  84531. return result;
  84532. };
  84533. return VRCameraMetrics;
  84534. }());
  84535. BABYLON.VRCameraMetrics = VRCameraMetrics;
  84536. })(BABYLON || (BABYLON = {}));
  84537. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  84538. "use strict";
  84539. var BABYLON;
  84540. (function (BABYLON) {
  84541. /**
  84542. * This represents a WebVR camera.
  84543. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  84544. * @example http://doc.babylonjs.com/how_to/webvr_camera
  84545. */
  84546. var WebVRFreeCamera = /** @class */ (function (_super) {
  84547. __extends(WebVRFreeCamera, _super);
  84548. /**
  84549. * Instantiates a WebVRFreeCamera.
  84550. * @param name The name of the WebVRFreeCamera
  84551. * @param position The starting anchor position for the camera
  84552. * @param scene The scene the camera belongs to
  84553. * @param webVROptions a set of customizable options for the webVRCamera
  84554. */
  84555. function WebVRFreeCamera(name, position, scene, webVROptions) {
  84556. if (webVROptions === void 0) { webVROptions = {}; }
  84557. var _this = _super.call(this, name, position, scene) || this;
  84558. _this.webVROptions = webVROptions;
  84559. /**
  84560. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  84561. */
  84562. _this._vrDevice = null;
  84563. /**
  84564. * The rawPose of the vrDevice.
  84565. */
  84566. _this.rawPose = null;
  84567. _this._specsVersion = "1.1";
  84568. _this._attached = false;
  84569. _this._descendants = [];
  84570. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  84571. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  84572. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  84573. _this._standingMatrix = null;
  84574. /**
  84575. * Represents device position in babylon space.
  84576. */
  84577. _this.devicePosition = BABYLON.Vector3.Zero();
  84578. /**
  84579. * Represents device rotation in babylon space.
  84580. */
  84581. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  84582. /**
  84583. * The scale of the device to be used when translating from device space to babylon space.
  84584. */
  84585. _this.deviceScaleFactor = 1;
  84586. _this._deviceToWorld = BABYLON.Matrix.Identity();
  84587. _this._worldToDevice = BABYLON.Matrix.Identity();
  84588. /**
  84589. * References to the webVR controllers for the vrDevice.
  84590. */
  84591. _this.controllers = [];
  84592. /**
  84593. * Emits an event when a controller is attached.
  84594. */
  84595. _this.onControllersAttachedObservable = new BABYLON.Observable();
  84596. /**
  84597. * Emits an event when a controller's mesh has been loaded;
  84598. */
  84599. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  84600. /**
  84601. * If the rig cameras be used as parent instead of this camera.
  84602. */
  84603. _this.rigParenting = true;
  84604. _this._defaultHeight = undefined;
  84605. _this._workingVector = BABYLON.Vector3.Zero();
  84606. _this._oneVector = BABYLON.Vector3.One();
  84607. _this._workingMatrix = BABYLON.Matrix.Identity();
  84608. _this._cache.position = BABYLON.Vector3.Zero();
  84609. if (webVROptions.defaultHeight) {
  84610. _this._defaultHeight = webVROptions.defaultHeight;
  84611. _this.position.y = _this._defaultHeight;
  84612. }
  84613. _this.minZ = 0.1;
  84614. //legacy support - the compensation boolean was removed.
  84615. if (arguments.length === 5) {
  84616. _this.webVROptions = arguments[4];
  84617. }
  84618. // default webVR options
  84619. if (_this.webVROptions.trackPosition == undefined) {
  84620. _this.webVROptions.trackPosition = true;
  84621. }
  84622. if (_this.webVROptions.controllerMeshes == undefined) {
  84623. _this.webVROptions.controllerMeshes = true;
  84624. }
  84625. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  84626. _this.webVROptions.defaultLightingOnControllers = true;
  84627. }
  84628. _this.rotationQuaternion = new BABYLON.Quaternion();
  84629. if (_this.webVROptions && _this.webVROptions.positionScale) {
  84630. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  84631. }
  84632. //enable VR
  84633. var engine = _this.getEngine();
  84634. _this._onVREnabled = function (success) { if (success) {
  84635. _this.initControllers();
  84636. } };
  84637. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  84638. engine.initWebVR().add(function (event) {
  84639. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  84640. return;
  84641. }
  84642. _this._vrDevice = event.vrDisplay;
  84643. //reset the rig parameters.
  84644. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  84645. if (_this._attached) {
  84646. _this.getEngine().enableVR();
  84647. }
  84648. });
  84649. if (typeof (VRFrameData) !== "undefined")
  84650. _this._frameData = new VRFrameData();
  84651. /**
  84652. * The idea behind the following lines:
  84653. * objects that have the camera as parent should actually have the rig cameras as a parent.
  84654. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  84655. * the second will not show it correctly.
  84656. *
  84657. * To solve this - each object that has the camera as parent will be added to a protected array.
  84658. * When the rig camera renders, it will take this array and set all of those to be its children.
  84659. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  84660. * Amazing!
  84661. */
  84662. scene.onBeforeCameraRenderObservable.add(function (camera) {
  84663. if (camera.parent === _this && _this.rigParenting) {
  84664. _this._descendants = _this.getDescendants(true, function (n) {
  84665. // don't take the cameras or the controllers!
  84666. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  84667. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  84668. return !isController && !isRigCamera;
  84669. });
  84670. _this._descendants.forEach(function (node) {
  84671. node.parent = camera;
  84672. });
  84673. }
  84674. });
  84675. scene.onAfterCameraRenderObservable.add(function (camera) {
  84676. if (camera.parent === _this && _this.rigParenting) {
  84677. _this._descendants.forEach(function (node) {
  84678. node.parent = _this;
  84679. });
  84680. }
  84681. });
  84682. return _this;
  84683. }
  84684. /**
  84685. * Gets the device distance from the ground in meters.
  84686. * @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.
  84687. */
  84688. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  84689. if (this._standingMatrix) {
  84690. // Add standing matrix offset to get real offset from ground in room
  84691. this._standingMatrix.getTranslationToRef(this._workingVector);
  84692. return this._deviceRoomPosition.y + this._workingVector.y;
  84693. }
  84694. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  84695. return this._defaultHeight || 0;
  84696. };
  84697. /**
  84698. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  84699. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  84700. */
  84701. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  84702. var _this = this;
  84703. if (callback === void 0) { callback = function (bool) { }; }
  84704. // Use standing matrix if available
  84705. this.getEngine().initWebVRAsync().then(function (result) {
  84706. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  84707. callback(false);
  84708. }
  84709. else {
  84710. _this._standingMatrix = new BABYLON.Matrix();
  84711. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  84712. if (!_this.getScene().useRightHandedSystem) {
  84713. [2, 6, 8, 9, 14].forEach(function (num) {
  84714. if (_this._standingMatrix) {
  84715. _this._standingMatrix.m[num] *= -1;
  84716. }
  84717. });
  84718. }
  84719. callback(true);
  84720. }
  84721. });
  84722. };
  84723. /**
  84724. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  84725. * @returns A promise with a boolean set to if the standing matrix is supported.
  84726. */
  84727. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  84728. var _this = this;
  84729. return new Promise(function (res, rej) {
  84730. _this.useStandingMatrix(function (supported) {
  84731. res(supported);
  84732. });
  84733. });
  84734. };
  84735. /**
  84736. * Disposes the camera
  84737. */
  84738. WebVRFreeCamera.prototype.dispose = function () {
  84739. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  84740. _super.prototype.dispose.call(this);
  84741. };
  84742. /**
  84743. * Gets a vrController by name.
  84744. * @param name The name of the controller to retreive
  84745. * @returns the controller matching the name specified or null if not found
  84746. */
  84747. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  84748. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  84749. var gp = _a[_i];
  84750. if (gp.hand === name) {
  84751. return gp;
  84752. }
  84753. }
  84754. return null;
  84755. };
  84756. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  84757. /**
  84758. * The controller corrisponding to the users left hand.
  84759. */
  84760. get: function () {
  84761. if (!this._leftController) {
  84762. this._leftController = this.getControllerByName("left");
  84763. }
  84764. return this._leftController;
  84765. },
  84766. enumerable: true,
  84767. configurable: true
  84768. });
  84769. ;
  84770. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  84771. /**
  84772. * The controller corrisponding to the users right hand.
  84773. */
  84774. get: function () {
  84775. if (!this._rightController) {
  84776. this._rightController = this.getControllerByName("right");
  84777. }
  84778. return this._rightController;
  84779. },
  84780. enumerable: true,
  84781. configurable: true
  84782. });
  84783. ;
  84784. /**
  84785. * Casts a ray forward from the vrCamera's gaze.
  84786. * @param length Length of the ray (default: 100)
  84787. * @returns the ray corrisponding to the gaze
  84788. */
  84789. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  84790. if (length === void 0) { length = 100; }
  84791. if (this.leftCamera) {
  84792. // Use left eye to avoid computation to compute center on every call
  84793. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  84794. }
  84795. else {
  84796. return _super.prototype.getForwardRay.call(this, length);
  84797. }
  84798. };
  84799. /**
  84800. * Updates the camera based on device's frame data
  84801. */
  84802. WebVRFreeCamera.prototype._checkInputs = function () {
  84803. if (this._vrDevice && this._vrDevice.isPresenting) {
  84804. this._vrDevice.getFrameData(this._frameData);
  84805. this.updateFromDevice(this._frameData.pose);
  84806. }
  84807. _super.prototype._checkInputs.call(this);
  84808. };
  84809. /**
  84810. * Updates the poseControlled values based on the input device pose.
  84811. * @param poseData Pose coming from the device
  84812. */
  84813. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  84814. if (poseData && poseData.orientation) {
  84815. this.rawPose = poseData;
  84816. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  84817. if (this.getScene().useRightHandedSystem) {
  84818. this._deviceRoomRotationQuaternion.z *= -1;
  84819. this._deviceRoomRotationQuaternion.w *= -1;
  84820. }
  84821. if (this.webVROptions.trackPosition && this.rawPose.position) {
  84822. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  84823. if (this.getScene().useRightHandedSystem) {
  84824. this._deviceRoomPosition.z *= -1;
  84825. }
  84826. }
  84827. }
  84828. };
  84829. /**
  84830. * WebVR's attach control will start broadcasting frames to the device.
  84831. * Note that in certain browsers (chrome for example) this function must be called
  84832. * within a user-interaction callback. Example:
  84833. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  84834. *
  84835. * @param element html element to attach the vrDevice to
  84836. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  84837. */
  84838. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  84839. _super.prototype.attachControl.call(this, element, noPreventDefault);
  84840. this._attached = true;
  84841. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  84842. if (this._vrDevice) {
  84843. this.getEngine().enableVR();
  84844. }
  84845. };
  84846. /**
  84847. * Detaches the camera from the html element and disables VR
  84848. *
  84849. * @param element html element to detach from
  84850. */
  84851. WebVRFreeCamera.prototype.detachControl = function (element) {
  84852. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  84853. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  84854. _super.prototype.detachControl.call(this, element);
  84855. this._attached = false;
  84856. this.getEngine().disableVR();
  84857. };
  84858. /**
  84859. * @returns the name of this class
  84860. */
  84861. WebVRFreeCamera.prototype.getClassName = function () {
  84862. return "WebVRFreeCamera";
  84863. };
  84864. /**
  84865. * Calls resetPose on the vrDisplay
  84866. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  84867. */
  84868. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  84869. //uses the vrDisplay's "resetPose()".
  84870. //pitch and roll won't be affected.
  84871. this._vrDevice.resetPose();
  84872. };
  84873. /**
  84874. * Updates the rig cameras (left and right eye)
  84875. */
  84876. WebVRFreeCamera.prototype._updateRigCameras = function () {
  84877. var camLeft = this._rigCameras[0];
  84878. var camRight = this._rigCameras[1];
  84879. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  84880. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  84881. camLeft.position.copyFrom(this._deviceRoomPosition);
  84882. camRight.position.copyFrom(this._deviceRoomPosition);
  84883. };
  84884. /**
  84885. * Updates the cached values of the camera
  84886. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  84887. */
  84888. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  84889. var _this = this;
  84890. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  84891. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  84892. if (!this.updateCacheCalled) {
  84893. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  84894. this.updateCacheCalled = true;
  84895. this.update();
  84896. }
  84897. // Set working vector to the device position in room space rotated by the new rotation
  84898. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  84899. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  84900. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  84901. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  84902. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  84903. // Add translation from anchor position
  84904. this._deviceToWorld.getTranslationToRef(this._workingVector);
  84905. this._workingVector.addInPlace(this.position);
  84906. this._workingVector.subtractInPlace(this._cache.position);
  84907. this._deviceToWorld.setTranslation(this._workingVector);
  84908. // Set an inverted matrix to be used when updating the camera
  84909. this._deviceToWorld.invertToRef(this._worldToDevice);
  84910. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  84911. this.controllers.forEach(function (controller) {
  84912. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  84913. controller.update();
  84914. });
  84915. }
  84916. if (!ignoreParentClass) {
  84917. _super.prototype._updateCache.call(this);
  84918. }
  84919. this.updateCacheCalled = false;
  84920. };
  84921. /**
  84922. * Updates the current device position and rotation in the babylon world
  84923. */
  84924. WebVRFreeCamera.prototype.update = function () {
  84925. // Get current device position in babylon world
  84926. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  84927. // Get current device rotation in babylon world
  84928. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  84929. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  84930. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  84931. _super.prototype.update.call(this);
  84932. };
  84933. /**
  84934. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  84935. * @returns an identity matrix
  84936. */
  84937. WebVRFreeCamera.prototype._getViewMatrix = function () {
  84938. return BABYLON.Matrix.Identity();
  84939. };
  84940. /**
  84941. * This function is called by the two RIG cameras.
  84942. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  84943. */
  84944. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  84945. var _this = this;
  84946. // Update the parent camera prior to using a child camera to avoid desynchronization
  84947. var parentCamera = this._cameraRigParams["parentCamera"];
  84948. parentCamera._updateCache();
  84949. //WebVR 1.1
  84950. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  84951. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  84952. if (!this.getScene().useRightHandedSystem) {
  84953. [2, 6, 8, 9, 14].forEach(function (num) {
  84954. _this._webvrViewMatrix.m[num] *= -1;
  84955. });
  84956. }
  84957. // update the camera rotation matrix
  84958. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  84959. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  84960. // Computing target and final matrix
  84961. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  84962. // should the view matrix be updated with scale and position offset?
  84963. if (parentCamera.deviceScaleFactor !== 1) {
  84964. this._webvrViewMatrix.invert();
  84965. // scale the position, if set
  84966. if (parentCamera.deviceScaleFactor) {
  84967. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  84968. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  84969. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  84970. }
  84971. this._webvrViewMatrix.invert();
  84972. }
  84973. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  84974. return this._webvrViewMatrix;
  84975. };
  84976. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  84977. var _this = this;
  84978. var parentCamera = this.parent;
  84979. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  84980. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  84981. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  84982. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  84983. //babylon compatible matrix
  84984. if (!this.getScene().useRightHandedSystem) {
  84985. [8, 9, 10, 11].forEach(function (num) {
  84986. _this._projectionMatrix.m[num] *= -1;
  84987. });
  84988. }
  84989. return this._projectionMatrix;
  84990. };
  84991. /**
  84992. * Initializes the controllers and their meshes
  84993. */
  84994. WebVRFreeCamera.prototype.initControllers = function () {
  84995. var _this = this;
  84996. this.controllers = [];
  84997. var manager = this.getScene().gamepadManager;
  84998. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  84999. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  85000. var webVrController = gamepad;
  85001. if (webVrController.defaultModel) {
  85002. webVrController.defaultModel.setEnabled(false);
  85003. }
  85004. if (webVrController.hand === "right") {
  85005. _this._rightController = null;
  85006. }
  85007. if (webVrController.hand === "left") {
  85008. _this._leftController = null;
  85009. }
  85010. var controllerIndex = _this.controllers.indexOf(webVrController);
  85011. if (controllerIndex !== -1) {
  85012. _this.controllers.splice(controllerIndex, 1);
  85013. }
  85014. }
  85015. });
  85016. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  85017. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  85018. var webVrController_1 = gamepad;
  85019. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  85020. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  85021. if (_this.webVROptions.controllerMeshes) {
  85022. if (webVrController_1.defaultModel) {
  85023. webVrController_1.defaultModel.setEnabled(true);
  85024. }
  85025. else {
  85026. // Load the meshes
  85027. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  85028. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  85029. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  85030. if (_this.webVROptions.defaultLightingOnControllers) {
  85031. if (!_this._lightOnControllers) {
  85032. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  85033. }
  85034. var activateLightOnSubMeshes_1 = function (mesh, light) {
  85035. var children = mesh.getChildren();
  85036. if (children.length !== 0) {
  85037. children.forEach(function (mesh) {
  85038. light.includedOnlyMeshes.push(mesh);
  85039. activateLightOnSubMeshes_1(mesh, light);
  85040. });
  85041. }
  85042. };
  85043. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  85044. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  85045. }
  85046. });
  85047. }
  85048. }
  85049. webVrController_1.attachToPoseControlledCamera(_this);
  85050. // since this is async - sanity check. Is the controller already stored?
  85051. if (_this.controllers.indexOf(webVrController_1) === -1) {
  85052. //add to the controllers array
  85053. _this.controllers.push(webVrController_1);
  85054. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  85055. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  85056. // So we're overriding setting left & right manually to be sure
  85057. var firstViveWandDetected = false;
  85058. for (var i = 0; i < _this.controllers.length; i++) {
  85059. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  85060. if (!firstViveWandDetected) {
  85061. firstViveWandDetected = true;
  85062. _this.controllers[i].hand = "left";
  85063. }
  85064. else {
  85065. _this.controllers[i].hand = "right";
  85066. }
  85067. }
  85068. }
  85069. //did we find enough controllers? Great! let the developer know.
  85070. if (_this.controllers.length >= 2) {
  85071. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  85072. }
  85073. }
  85074. }
  85075. });
  85076. };
  85077. return WebVRFreeCamera;
  85078. }(BABYLON.FreeCamera));
  85079. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  85080. })(BABYLON || (BABYLON = {}));
  85081. //# sourceMappingURL=babylon.webVRCamera.js.map
  85082. "use strict";
  85083. var BABYLON;
  85084. (function (BABYLON) {
  85085. // We're mainly based on the logic defined into the FreeCamera code
  85086. /**
  85087. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  85088. * being tilted forward or back and left or right.
  85089. */
  85090. var DeviceOrientationCamera = /** @class */ (function (_super) {
  85091. __extends(DeviceOrientationCamera, _super);
  85092. /**
  85093. * Creates a new device orientation camera
  85094. * @param name The name of the camera
  85095. * @param position The start position camera
  85096. * @param scene The scene the camera belongs to
  85097. */
  85098. function DeviceOrientationCamera(name, position, scene) {
  85099. var _this = _super.call(this, name, position, scene) || this;
  85100. _this._quaternionCache = new BABYLON.Quaternion();
  85101. _this.inputs.addDeviceOrientation();
  85102. return _this;
  85103. }
  85104. /**
  85105. * Gets the current instance class name ("DeviceOrientationCamera").
  85106. * This helps avoiding instanceof at run time.
  85107. * @returns the class name
  85108. */
  85109. DeviceOrientationCamera.prototype.getClassName = function () {
  85110. return "DeviceOrientationCamera";
  85111. };
  85112. /**
  85113. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  85114. */
  85115. DeviceOrientationCamera.prototype._checkInputs = function () {
  85116. _super.prototype._checkInputs.call(this);
  85117. this._quaternionCache.copyFrom(this.rotationQuaternion);
  85118. if (this._initialQuaternion) {
  85119. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  85120. }
  85121. };
  85122. /**
  85123. * Reset the camera to its default orientation on the specified axis only.
  85124. * @param axis The axis to reset
  85125. */
  85126. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  85127. var _this = this;
  85128. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  85129. //can only work if this camera has a rotation quaternion already.
  85130. if (!this.rotationQuaternion)
  85131. return;
  85132. if (!this._initialQuaternion) {
  85133. this._initialQuaternion = new BABYLON.Quaternion();
  85134. }
  85135. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  85136. ['x', 'y', 'z'].forEach(function (axisName) {
  85137. if (!axis[axisName]) {
  85138. _this._initialQuaternion[axisName] = 0;
  85139. }
  85140. else {
  85141. _this._initialQuaternion[axisName] *= -1;
  85142. }
  85143. });
  85144. this._initialQuaternion.normalize();
  85145. //force rotation update
  85146. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  85147. };
  85148. return DeviceOrientationCamera;
  85149. }(BABYLON.FreeCamera));
  85150. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  85151. })(BABYLON || (BABYLON = {}));
  85152. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  85153. "use strict";
  85154. var BABYLON;
  85155. (function (BABYLON) {
  85156. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  85157. __extends(VRDeviceOrientationFreeCamera, _super);
  85158. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  85159. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85160. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85161. var _this = _super.call(this, name, position, scene) || this;
  85162. vrCameraMetrics.compensateDistortion = compensateDistortion;
  85163. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  85164. return _this;
  85165. }
  85166. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  85167. return "VRDeviceOrientationFreeCamera";
  85168. };
  85169. return VRDeviceOrientationFreeCamera;
  85170. }(BABYLON.DeviceOrientationCamera));
  85171. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  85172. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  85173. __extends(VRDeviceOrientationGamepadCamera, _super);
  85174. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  85175. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85176. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85177. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  85178. _this.inputs.addGamepad();
  85179. return _this;
  85180. }
  85181. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  85182. return "VRDeviceOrientationGamepadCamera";
  85183. };
  85184. return VRDeviceOrientationGamepadCamera;
  85185. }(VRDeviceOrientationFreeCamera));
  85186. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  85187. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  85188. __extends(VRDeviceOrientationArcRotateCamera, _super);
  85189. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  85190. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85191. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85192. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85193. vrCameraMetrics.compensateDistortion = compensateDistortion;
  85194. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  85195. _this.inputs.addVRDeviceOrientation();
  85196. return _this;
  85197. }
  85198. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  85199. return "VRDeviceOrientationArcRotateCamera";
  85200. };
  85201. return VRDeviceOrientationArcRotateCamera;
  85202. }(BABYLON.ArcRotateCamera));
  85203. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  85204. })(BABYLON || (BABYLON = {}));
  85205. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  85206. "use strict";
  85207. var BABYLON;
  85208. (function (BABYLON) {
  85209. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  85210. __extends(AnaglyphFreeCamera, _super);
  85211. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  85212. var _this = _super.call(this, name, position, scene) || this;
  85213. _this.interaxialDistance = interaxialDistance;
  85214. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85215. return _this;
  85216. }
  85217. AnaglyphFreeCamera.prototype.getClassName = function () {
  85218. return "AnaglyphFreeCamera";
  85219. };
  85220. return AnaglyphFreeCamera;
  85221. }(BABYLON.FreeCamera));
  85222. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  85223. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  85224. __extends(AnaglyphArcRotateCamera, _super);
  85225. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  85226. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85227. _this.interaxialDistance = interaxialDistance;
  85228. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85229. return _this;
  85230. }
  85231. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  85232. return "AnaglyphArcRotateCamera";
  85233. };
  85234. return AnaglyphArcRotateCamera;
  85235. }(BABYLON.ArcRotateCamera));
  85236. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  85237. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  85238. __extends(AnaglyphGamepadCamera, _super);
  85239. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  85240. var _this = _super.call(this, name, position, scene) || this;
  85241. _this.interaxialDistance = interaxialDistance;
  85242. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85243. return _this;
  85244. }
  85245. AnaglyphGamepadCamera.prototype.getClassName = function () {
  85246. return "AnaglyphGamepadCamera";
  85247. };
  85248. return AnaglyphGamepadCamera;
  85249. }(BABYLON.GamepadCamera));
  85250. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  85251. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  85252. __extends(AnaglyphUniversalCamera, _super);
  85253. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  85254. var _this = _super.call(this, name, position, scene) || this;
  85255. _this.interaxialDistance = interaxialDistance;
  85256. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85257. return _this;
  85258. }
  85259. AnaglyphUniversalCamera.prototype.getClassName = function () {
  85260. return "AnaglyphUniversalCamera";
  85261. };
  85262. return AnaglyphUniversalCamera;
  85263. }(BABYLON.UniversalCamera));
  85264. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  85265. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  85266. __extends(StereoscopicFreeCamera, _super);
  85267. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85268. var _this = _super.call(this, name, position, scene) || this;
  85269. _this.interaxialDistance = interaxialDistance;
  85270. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85271. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85272. return _this;
  85273. }
  85274. StereoscopicFreeCamera.prototype.getClassName = function () {
  85275. return "StereoscopicFreeCamera";
  85276. };
  85277. return StereoscopicFreeCamera;
  85278. }(BABYLON.FreeCamera));
  85279. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  85280. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  85281. __extends(StereoscopicArcRotateCamera, _super);
  85282. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  85283. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85284. _this.interaxialDistance = interaxialDistance;
  85285. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85286. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85287. return _this;
  85288. }
  85289. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  85290. return "StereoscopicArcRotateCamera";
  85291. };
  85292. return StereoscopicArcRotateCamera;
  85293. }(BABYLON.ArcRotateCamera));
  85294. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  85295. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  85296. __extends(StereoscopicGamepadCamera, _super);
  85297. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85298. var _this = _super.call(this, name, position, scene) || this;
  85299. _this.interaxialDistance = interaxialDistance;
  85300. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85301. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85302. return _this;
  85303. }
  85304. StereoscopicGamepadCamera.prototype.getClassName = function () {
  85305. return "StereoscopicGamepadCamera";
  85306. };
  85307. return StereoscopicGamepadCamera;
  85308. }(BABYLON.GamepadCamera));
  85309. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  85310. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  85311. __extends(StereoscopicUniversalCamera, _super);
  85312. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85313. var _this = _super.call(this, name, position, scene) || this;
  85314. _this.interaxialDistance = interaxialDistance;
  85315. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85316. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85317. return _this;
  85318. }
  85319. StereoscopicUniversalCamera.prototype.getClassName = function () {
  85320. return "StereoscopicUniversalCamera";
  85321. };
  85322. return StereoscopicUniversalCamera;
  85323. }(BABYLON.UniversalCamera));
  85324. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  85325. })(BABYLON || (BABYLON = {}));
  85326. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  85327. "use strict";
  85328. var BABYLON;
  85329. (function (BABYLON) {
  85330. var VRExperienceHelperGazer = /** @class */ (function () {
  85331. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  85332. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  85333. this.scene = scene;
  85334. this._pointerDownOnMeshAsked = false;
  85335. this._isActionableMesh = false;
  85336. this._teleportationRequestInitiated = false;
  85337. this._teleportationBackRequestInitiated = false;
  85338. this._dpadPressed = true;
  85339. this._activePointer = false;
  85340. this._id = VRExperienceHelperGazer._idCounter++;
  85341. // Gaze tracker
  85342. if (!gazeTrackerToClone) {
  85343. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  85344. this._gazeTracker.bakeCurrentTransformIntoVertices();
  85345. this._gazeTracker.isPickable = false;
  85346. this._gazeTracker.isVisible = false;
  85347. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  85348. targetMat.specularColor = BABYLON.Color3.Black();
  85349. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  85350. targetMat.backFaceCulling = false;
  85351. this._gazeTracker.material = targetMat;
  85352. }
  85353. else {
  85354. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  85355. }
  85356. }
  85357. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  85358. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  85359. };
  85360. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  85361. this._pointerDownOnMeshAsked = true;
  85362. if (this._currentMeshSelected && this._currentHit) {
  85363. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  85364. }
  85365. };
  85366. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  85367. if (this._currentMeshSelected && this._currentHit) {
  85368. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  85369. }
  85370. this._pointerDownOnMeshAsked = false;
  85371. };
  85372. VRExperienceHelperGazer.prototype._activatePointer = function () {
  85373. this._activePointer = true;
  85374. };
  85375. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  85376. this._activePointer = false;
  85377. };
  85378. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  85379. };
  85380. VRExperienceHelperGazer.prototype.dispose = function () {
  85381. this._interactionsEnabled = false;
  85382. this._teleportationEnabled = false;
  85383. };
  85384. VRExperienceHelperGazer._idCounter = 0;
  85385. return VRExperienceHelperGazer;
  85386. }());
  85387. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  85388. __extends(VRExperienceHelperControllerGazer, _super);
  85389. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  85390. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  85391. _this.webVRController = webVRController;
  85392. // Laser pointer
  85393. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  85394. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  85395. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  85396. laserPointerMaterial.alpha = 0.6;
  85397. _this._laserPointer.material = laserPointerMaterial;
  85398. _this._laserPointer.rotation.x = Math.PI / 2;
  85399. _this._laserPointer.position.z = -0.5;
  85400. _this._laserPointer.isVisible = false;
  85401. if (!webVRController.mesh) {
  85402. // Create an empty mesh that is used prior to loading the high quality model
  85403. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  85404. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  85405. preloadPointerPose.rotation.x = -0.7;
  85406. preloadMesh.addChild(preloadPointerPose);
  85407. webVRController.attachToMesh(preloadMesh);
  85408. }
  85409. _this._setLaserPointerParent(webVRController.mesh);
  85410. return _this;
  85411. }
  85412. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  85413. return this.webVRController.getForwardRay(length);
  85414. };
  85415. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  85416. _super.prototype._activatePointer.call(this);
  85417. this._laserPointer.isVisible = true;
  85418. };
  85419. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  85420. _super.prototype._deactivatePointer.call(this);
  85421. this._laserPointer.isVisible = false;
  85422. };
  85423. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  85424. this._laserPointer.material.emissiveColor = color;
  85425. };
  85426. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  85427. var makeNotPick = function (root) {
  85428. root.name += " laserPointer";
  85429. root.getChildMeshes().forEach(function (c) {
  85430. makeNotPick(c);
  85431. });
  85432. };
  85433. makeNotPick(mesh);
  85434. var childMeshes = mesh.getChildMeshes();
  85435. this.webVRController._pointingPoseNode = null;
  85436. for (var i = 0; i < childMeshes.length; i++) {
  85437. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  85438. mesh = childMeshes[i];
  85439. this.webVRController._pointingPoseNode = mesh;
  85440. break;
  85441. }
  85442. }
  85443. this._laserPointer.parent = mesh;
  85444. };
  85445. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  85446. this._laserPointer.scaling.y = distance;
  85447. this._laserPointer.position.z = -distance / 2;
  85448. };
  85449. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  85450. _super.prototype.dispose.call(this);
  85451. this._laserPointer.dispose();
  85452. };
  85453. return VRExperienceHelperControllerGazer;
  85454. }(VRExperienceHelperGazer));
  85455. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  85456. __extends(VRExperienceHelperCameraGazer, _super);
  85457. function VRExperienceHelperCameraGazer(getCamera, scene) {
  85458. var _this = _super.call(this, scene) || this;
  85459. _this.getCamera = getCamera;
  85460. return _this;
  85461. }
  85462. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  85463. var camera = this.getCamera();
  85464. if (camera) {
  85465. return camera.getForwardRay(length);
  85466. }
  85467. else {
  85468. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  85469. }
  85470. };
  85471. return VRExperienceHelperCameraGazer;
  85472. }(VRExperienceHelperGazer));
  85473. /**
  85474. * Helps to quickly add VR support to an existing scene.
  85475. * See http://doc.babylonjs.com/how_to/webvr_helper
  85476. */
  85477. var VRExperienceHelper = /** @class */ (function () {
  85478. /**
  85479. * Instantiates a VRExperienceHelper.
  85480. * Helps to quickly add VR support to an existing scene.
  85481. * @param scene The scene the VRExperienceHelper belongs to.
  85482. * @param webVROptions Options to modify the vr experience helper's behavior.
  85483. */
  85484. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  85485. if (webVROptions === void 0) { webVROptions = {}; }
  85486. var _this = this;
  85487. this.webVROptions = webVROptions;
  85488. // Can the system support WebVR, even if a headset isn't plugged in?
  85489. this._webVRsupported = false;
  85490. // If WebVR is supported, is a headset plugged in and are we ready to present?
  85491. this._webVRready = false;
  85492. // Are we waiting for the requestPresent callback to complete?
  85493. this._webVRrequesting = false;
  85494. // Are we presenting to the headset right now?
  85495. this._webVRpresenting = false;
  85496. // Are we presenting in the fullscreen fallback?
  85497. this._fullscreenVRpresenting = false;
  85498. /**
  85499. * Observable raised when entering VR.
  85500. */
  85501. this.onEnteringVRObservable = new BABYLON.Observable();
  85502. /**
  85503. * Observable raised when exiting VR.
  85504. */
  85505. this.onExitingVRObservable = new BABYLON.Observable();
  85506. /**
  85507. * Observable raised when controller mesh is loaded.
  85508. */
  85509. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85510. this._useCustomVRButton = false;
  85511. this._teleportationRequested = false;
  85512. this._teleportActive = false;
  85513. this._floorMeshesCollection = [];
  85514. this._rotationAllowed = true;
  85515. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  85516. this._rotationRightAsked = false;
  85517. this._rotationLeftAsked = false;
  85518. this._isDefaultTeleportationTarget = true;
  85519. this._teleportationFillColor = "#444444";
  85520. this._teleportationBorderColor = "#FFFFFF";
  85521. this._rotationAngle = 0;
  85522. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  85523. this._padSensibilityUp = 0.65;
  85524. this._padSensibilityDown = 0.35;
  85525. this.leftController = null;
  85526. this.rightController = null;
  85527. /**
  85528. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  85529. */
  85530. this.onNewMeshSelected = new BABYLON.Observable();
  85531. /**
  85532. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  85533. */
  85534. this.onNewMeshPicked = new BABYLON.Observable();
  85535. /**
  85536. * Observable raised before camera teleportation
  85537. */
  85538. this.onBeforeCameraTeleport = new BABYLON.Observable();
  85539. /**
  85540. * Observable raised after camera teleportation
  85541. */
  85542. this.onAfterCameraTeleport = new BABYLON.Observable();
  85543. /**
  85544. * Observable raised when current selected mesh gets unselected
  85545. */
  85546. this.onSelectedMeshUnselected = new BABYLON.Observable();
  85547. /**
  85548. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  85549. */
  85550. this.teleportationEnabled = true;
  85551. this._teleportationInitialized = false;
  85552. this._interactionsEnabled = false;
  85553. this._interactionsRequested = false;
  85554. this._displayGaze = true;
  85555. this._displayLaserPointer = true;
  85556. this._onResize = function () {
  85557. _this.moveButtonToBottomRight();
  85558. if (_this._fullscreenVRpresenting && _this._webVRready) {
  85559. _this.exitVR();
  85560. }
  85561. };
  85562. this._onFullscreenChange = function () {
  85563. if (document.fullscreen !== undefined) {
  85564. _this._fullscreenVRpresenting = document.fullscreen;
  85565. }
  85566. else if (document.mozFullScreen !== undefined) {
  85567. _this._fullscreenVRpresenting = document.mozFullScreen;
  85568. }
  85569. else if (document.webkitIsFullScreen !== undefined) {
  85570. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  85571. }
  85572. else if (document.msIsFullScreen !== undefined) {
  85573. _this._fullscreenVRpresenting = document.msIsFullScreen;
  85574. }
  85575. if (!_this._fullscreenVRpresenting && _this._canvas) {
  85576. _this.exitVR();
  85577. if (!_this._useCustomVRButton) {
  85578. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  85579. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  85580. }
  85581. }
  85582. };
  85583. this.beforeRender = function () {
  85584. if (_this.leftController && _this.leftController._activePointer) {
  85585. _this._castRayAndSelectObject(_this.leftController);
  85586. }
  85587. if (_this.rightController && _this.rightController._activePointer) {
  85588. _this._castRayAndSelectObject(_this.rightController);
  85589. }
  85590. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  85591. _this._castRayAndSelectObject(_this._cameraGazer);
  85592. }
  85593. else {
  85594. _this._cameraGazer._gazeTracker.isVisible = false;
  85595. }
  85596. };
  85597. this._onNewGamepadConnected = function (gamepad) {
  85598. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  85599. if (gamepad.leftStick) {
  85600. gamepad.onleftstickchanged(function (stickValues) {
  85601. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  85602. // Listening to classic/xbox gamepad only if no VR controller is active
  85603. if ((!_this.leftController && !_this.rightController) ||
  85604. ((_this.leftController && !_this.leftController._activePointer) &&
  85605. (_this.rightController && !_this.rightController._activePointer))) {
  85606. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  85607. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  85608. }
  85609. }
  85610. });
  85611. }
  85612. if (gamepad.rightStick) {
  85613. gamepad.onrightstickchanged(function (stickValues) {
  85614. if (_this._teleportationInitialized) {
  85615. _this._checkRotate(stickValues, _this._cameraGazer);
  85616. }
  85617. });
  85618. }
  85619. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  85620. gamepad.onbuttondown(function (buttonPressed) {
  85621. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  85622. _this._cameraGazer._selectionPointerDown();
  85623. }
  85624. });
  85625. gamepad.onbuttonup(function (buttonPressed) {
  85626. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  85627. _this._cameraGazer._selectionPointerUp();
  85628. }
  85629. });
  85630. }
  85631. }
  85632. else {
  85633. var webVRController = gamepad;
  85634. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  85635. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  85636. _this.rightController = controller;
  85637. }
  85638. else {
  85639. _this.leftController = controller;
  85640. }
  85641. _this._tryEnableInteractionOnController(controller);
  85642. }
  85643. };
  85644. // 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
  85645. this._tryEnableInteractionOnController = function (controller) {
  85646. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  85647. _this._enableInteractionOnController(controller);
  85648. }
  85649. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  85650. _this._enableTeleportationOnController(controller);
  85651. }
  85652. };
  85653. this._onNewGamepadDisconnected = function (gamepad) {
  85654. if (gamepad instanceof BABYLON.WebVRController) {
  85655. if (gamepad.hand === "left" && _this.leftController != null) {
  85656. _this.leftController.dispose();
  85657. _this.leftController = null;
  85658. }
  85659. if (gamepad.hand === "right" && _this.rightController != null) {
  85660. _this.rightController.dispose();
  85661. _this.rightController = null;
  85662. }
  85663. }
  85664. };
  85665. this._workingVector = BABYLON.Vector3.Zero();
  85666. this._workingQuaternion = BABYLON.Quaternion.Identity();
  85667. this._workingMatrix = BABYLON.Matrix.Identity();
  85668. this._scene = scene;
  85669. this._canvas = scene.getEngine().getRenderingCanvas();
  85670. // Parse options
  85671. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  85672. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  85673. }
  85674. if (webVROptions.createDeviceOrientationCamera === undefined) {
  85675. webVROptions.createDeviceOrientationCamera = true;
  85676. }
  85677. if (webVROptions.defaultHeight === undefined) {
  85678. webVROptions.defaultHeight = 1.7;
  85679. }
  85680. if (webVROptions.useCustomVRButton) {
  85681. this._useCustomVRButton = true;
  85682. if (webVROptions.customVRButton) {
  85683. this._btnVR = webVROptions.customVRButton;
  85684. }
  85685. }
  85686. if (webVROptions.rayLength) {
  85687. this._rayLength = webVROptions.rayLength;
  85688. }
  85689. this._defaultHeight = webVROptions.defaultHeight;
  85690. if (webVROptions.positionScale) {
  85691. this._rayLength *= webVROptions.positionScale;
  85692. this._defaultHeight *= webVROptions.positionScale;
  85693. }
  85694. // Set position
  85695. if (this._scene.activeCamera) {
  85696. this._position = this._scene.activeCamera.position.clone();
  85697. }
  85698. else {
  85699. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  85700. }
  85701. // Set non-vr camera
  85702. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  85703. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  85704. // Copy data from existing camera
  85705. if (this._scene.activeCamera) {
  85706. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  85707. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  85708. // Set rotation from previous camera
  85709. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  85710. var targetCamera = this._scene.activeCamera;
  85711. if (targetCamera.rotationQuaternion) {
  85712. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  85713. }
  85714. else {
  85715. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  85716. }
  85717. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  85718. }
  85719. }
  85720. this._scene.activeCamera = this._deviceOrientationCamera;
  85721. if (this._canvas) {
  85722. this._scene.activeCamera.attachControl(this._canvas);
  85723. }
  85724. }
  85725. else {
  85726. this._existingCamera = this._scene.activeCamera;
  85727. }
  85728. // Create VR cameras
  85729. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  85730. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  85731. }
  85732. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  85733. this._webVRCamera.useStandingMatrix();
  85734. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  85735. // Create default button
  85736. if (!this._useCustomVRButton) {
  85737. this._btnVR = document.createElement("BUTTON");
  85738. this._btnVR.className = "babylonVRicon";
  85739. this._btnVR.id = "babylonVRiconbtn";
  85740. this._btnVR.title = "Click to switch to VR";
  85741. 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) }";
  85742. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  85743. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  85744. // css += ".babylonVRicon.vrdisplaysupported { }";
  85745. // css += ".babylonVRicon.vrdisplayready { }";
  85746. // css += ".babylonVRicon.vrdisplayrequesting { }";
  85747. var style = document.createElement('style');
  85748. style.appendChild(document.createTextNode(css));
  85749. document.getElementsByTagName('head')[0].appendChild(style);
  85750. this.moveButtonToBottomRight();
  85751. }
  85752. // VR button click event
  85753. if (this._btnVR) {
  85754. this._btnVR.addEventListener("click", function () {
  85755. if (!_this.isInVRMode) {
  85756. _this.enterVR();
  85757. }
  85758. else {
  85759. _this.exitVR();
  85760. }
  85761. });
  85762. }
  85763. // Window events
  85764. window.addEventListener("resize", this._onResize);
  85765. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  85766. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  85767. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  85768. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  85769. // Display vr button when headset is connected
  85770. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  85771. this.displayVRButton();
  85772. }
  85773. else {
  85774. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  85775. if (e.vrDisplay) {
  85776. _this.displayVRButton();
  85777. }
  85778. });
  85779. }
  85780. // Exiting VR mode using 'ESC' key on desktop
  85781. this._onKeyDown = function (event) {
  85782. if (event.keyCode === 27 && _this.isInVRMode) {
  85783. _this.exitVR();
  85784. }
  85785. };
  85786. document.addEventListener("keydown", this._onKeyDown);
  85787. // Exiting VR mode double tapping the touch screen
  85788. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  85789. if (_this.isInVRMode) {
  85790. _this.exitVR();
  85791. if (_this._fullscreenVRpresenting) {
  85792. _this._scene.getEngine().switchFullscreen(true);
  85793. }
  85794. }
  85795. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  85796. // Listen for WebVR display changes
  85797. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  85798. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  85799. this._onVRRequestPresentStart = function () {
  85800. _this._webVRrequesting = true;
  85801. _this.updateButtonVisibility();
  85802. };
  85803. this._onVRRequestPresentComplete = function (success) {
  85804. _this._webVRrequesting = false;
  85805. _this.updateButtonVisibility();
  85806. };
  85807. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  85808. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  85809. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  85810. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  85811. scene.onDisposeObservable.add(function () {
  85812. _this.dispose();
  85813. });
  85814. // Gamepad connection events
  85815. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  85816. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  85817. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  85818. this.updateButtonVisibility();
  85819. //create easing functions
  85820. this._circleEase = new BABYLON.CircleEase();
  85821. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  85822. }
  85823. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  85824. /** Return this.onEnteringVRObservable
  85825. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  85826. */
  85827. get: function () {
  85828. return this.onEnteringVRObservable;
  85829. },
  85830. enumerable: true,
  85831. configurable: true
  85832. });
  85833. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  85834. /** Return this.onExitingVRObservable
  85835. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  85836. */
  85837. get: function () {
  85838. return this.onExitingVRObservable;
  85839. },
  85840. enumerable: true,
  85841. configurable: true
  85842. });
  85843. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  85844. /** Return this.onControllerMeshLoadedObservable
  85845. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  85846. */
  85847. get: function () {
  85848. return this.onControllerMeshLoadedObservable;
  85849. },
  85850. enumerable: true,
  85851. configurable: true
  85852. });
  85853. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  85854. /**
  85855. * The mesh used to display where the user is going to teleport.
  85856. */
  85857. get: function () {
  85858. return this._teleportationTarget;
  85859. },
  85860. /**
  85861. * Sets the mesh to be used to display where the user is going to teleport.
  85862. */
  85863. set: function (value) {
  85864. if (value) {
  85865. value.name = "teleportationTarget";
  85866. this._isDefaultTeleportationTarget = false;
  85867. this._teleportationTarget = value;
  85868. }
  85869. },
  85870. enumerable: true,
  85871. configurable: true
  85872. });
  85873. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  85874. /**
  85875. * The mesh used to display where the user is selecting,
  85876. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  85877. * See http://doc.babylonjs.com/resources/baking_transformations
  85878. */
  85879. get: function () {
  85880. return this._cameraGazer._gazeTracker;
  85881. },
  85882. set: function (value) {
  85883. if (value) {
  85884. this._cameraGazer._gazeTracker = value;
  85885. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  85886. this._cameraGazer._gazeTracker.isPickable = false;
  85887. this._cameraGazer._gazeTracker.isVisible = false;
  85888. this._cameraGazer._gazeTracker.name = "gazeTracker";
  85889. if (this.leftController) {
  85890. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  85891. }
  85892. if (this.rightController) {
  85893. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  85894. }
  85895. }
  85896. },
  85897. enumerable: true,
  85898. configurable: true
  85899. });
  85900. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  85901. /**
  85902. * If the ray of the gaze should be displayed.
  85903. */
  85904. get: function () {
  85905. return this._displayGaze;
  85906. },
  85907. /**
  85908. * Sets if the ray of the gaze should be displayed.
  85909. */
  85910. set: function (value) {
  85911. this._displayGaze = value;
  85912. if (!value) {
  85913. this._cameraGazer._gazeTracker.isVisible = false;
  85914. if (this.leftController) {
  85915. this.leftController._gazeTracker.isVisible = false;
  85916. }
  85917. if (this.rightController) {
  85918. this.rightController._gazeTracker.isVisible = false;
  85919. }
  85920. }
  85921. },
  85922. enumerable: true,
  85923. configurable: true
  85924. });
  85925. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  85926. /**
  85927. * If the ray of the LaserPointer should be displayed.
  85928. */
  85929. get: function () {
  85930. return this._displayLaserPointer;
  85931. },
  85932. /**
  85933. * Sets if the ray of the LaserPointer should be displayed.
  85934. */
  85935. set: function (value) {
  85936. this._displayLaserPointer = value;
  85937. if (!value) {
  85938. if (this.rightController) {
  85939. this.rightController._deactivatePointer();
  85940. this.rightController._gazeTracker.isVisible = false;
  85941. }
  85942. if (this.leftController) {
  85943. this.leftController._deactivatePointer();
  85944. this.leftController._gazeTracker.isVisible = false;
  85945. }
  85946. }
  85947. else {
  85948. if (this.rightController) {
  85949. this.rightController._activatePointer();
  85950. }
  85951. else if (this.leftController) {
  85952. this.leftController._activatePointer();
  85953. }
  85954. }
  85955. },
  85956. enumerable: true,
  85957. configurable: true
  85958. });
  85959. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  85960. /**
  85961. * The deviceOrientationCamera used as the camera when not in VR.
  85962. */
  85963. get: function () {
  85964. return this._deviceOrientationCamera;
  85965. },
  85966. enumerable: true,
  85967. configurable: true
  85968. });
  85969. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  85970. /**
  85971. * Based on the current WebVR support, returns the current VR camera used.
  85972. */
  85973. get: function () {
  85974. if (this._webVRready) {
  85975. return this._webVRCamera;
  85976. }
  85977. else {
  85978. return this._scene.activeCamera;
  85979. }
  85980. },
  85981. enumerable: true,
  85982. configurable: true
  85983. });
  85984. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  85985. /**
  85986. * The webVRCamera which is used when in VR.
  85987. */
  85988. get: function () {
  85989. return this._webVRCamera;
  85990. },
  85991. enumerable: true,
  85992. configurable: true
  85993. });
  85994. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  85995. /**
  85996. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  85997. */
  85998. get: function () {
  85999. return this._vrDeviceOrientationCamera;
  86000. },
  86001. enumerable: true,
  86002. configurable: true
  86003. });
  86004. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  86005. get: function () {
  86006. var result = this._cameraGazer._teleportationRequestInitiated
  86007. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  86008. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  86009. return result;
  86010. },
  86011. enumerable: true,
  86012. configurable: true
  86013. });
  86014. // Raised when one of the controller has loaded successfully its associated default mesh
  86015. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  86016. if (this.leftController && this.leftController.webVRController == webVRController) {
  86017. if (webVRController.mesh) {
  86018. this.leftController._setLaserPointerParent(webVRController.mesh);
  86019. }
  86020. }
  86021. if (this.rightController && this.rightController.webVRController == webVRController) {
  86022. if (webVRController.mesh) {
  86023. this.rightController._setLaserPointerParent(webVRController.mesh);
  86024. }
  86025. }
  86026. try {
  86027. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  86028. }
  86029. catch (err) {
  86030. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  86031. }
  86032. };
  86033. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  86034. /**
  86035. * Gets a value indicating if we are currently in VR mode.
  86036. */
  86037. get: function () {
  86038. return this._webVRpresenting || this._fullscreenVRpresenting;
  86039. },
  86040. enumerable: true,
  86041. configurable: true
  86042. });
  86043. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  86044. var vrDisplay = this._scene.getEngine().getVRDevice();
  86045. if (vrDisplay) {
  86046. var wasPresenting = this._webVRpresenting;
  86047. // A VR display is connected
  86048. this._webVRpresenting = vrDisplay.isPresenting;
  86049. if (wasPresenting && !this._webVRpresenting)
  86050. this.exitVR();
  86051. }
  86052. else {
  86053. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  86054. }
  86055. this.updateButtonVisibility();
  86056. };
  86057. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  86058. this._webVRsupported = eventArgs.vrSupported;
  86059. this._webVRready = !!eventArgs.vrDisplay;
  86060. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  86061. this.updateButtonVisibility();
  86062. };
  86063. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  86064. if (this._canvas && !this._useCustomVRButton) {
  86065. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  86066. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  86067. }
  86068. };
  86069. VRExperienceHelper.prototype.displayVRButton = function () {
  86070. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  86071. document.body.appendChild(this._btnVR);
  86072. this._btnVRDisplayed = true;
  86073. }
  86074. };
  86075. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  86076. if (!this._btnVR || this._useCustomVRButton) {
  86077. return;
  86078. }
  86079. this._btnVR.className = "babylonVRicon";
  86080. if (this.isInVRMode) {
  86081. this._btnVR.className += " vrdisplaypresenting";
  86082. }
  86083. else {
  86084. if (this._webVRready)
  86085. this._btnVR.className += " vrdisplayready";
  86086. if (this._webVRsupported)
  86087. this._btnVR.className += " vrdisplaysupported";
  86088. if (this._webVRrequesting)
  86089. this._btnVR.className += " vrdisplayrequesting";
  86090. }
  86091. };
  86092. /**
  86093. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  86094. * Otherwise, will use the fullscreen API.
  86095. */
  86096. VRExperienceHelper.prototype.enterVR = function () {
  86097. if (this.onEnteringVRObservable) {
  86098. try {
  86099. this.onEnteringVRObservable.notifyObservers(this);
  86100. }
  86101. catch (err) {
  86102. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  86103. }
  86104. }
  86105. if (this._scene.activeCamera) {
  86106. this._position = this._scene.activeCamera.position.clone();
  86107. // make sure that we return to the last active camera
  86108. this._existingCamera = this._scene.activeCamera;
  86109. }
  86110. if (this._webVRrequesting)
  86111. return;
  86112. // If WebVR is supported and a headset is connected
  86113. if (this._webVRready) {
  86114. if (!this._webVRpresenting) {
  86115. this._webVRCamera.position = this._position;
  86116. this._scene.activeCamera = this._webVRCamera;
  86117. }
  86118. }
  86119. else if (this._vrDeviceOrientationCamera) {
  86120. this._vrDeviceOrientationCamera.position = this._position;
  86121. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  86122. this._scene.getEngine().switchFullscreen(true);
  86123. this.updateButtonVisibility();
  86124. }
  86125. if (this._scene.activeCamera && this._canvas) {
  86126. this._scene.activeCamera.attachControl(this._canvas);
  86127. }
  86128. if (this._interactionsEnabled) {
  86129. this._scene.registerBeforeRender(this.beforeRender);
  86130. }
  86131. };
  86132. /**
  86133. * Attempt to exit VR, or fullscreen.
  86134. */
  86135. VRExperienceHelper.prototype.exitVR = function () {
  86136. if (this.onExitingVRObservable) {
  86137. try {
  86138. this.onExitingVRObservable.notifyObservers(this);
  86139. }
  86140. catch (err) {
  86141. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  86142. }
  86143. }
  86144. if (this._webVRpresenting) {
  86145. this._scene.getEngine().disableVR();
  86146. }
  86147. if (this._scene.activeCamera) {
  86148. this._position = this._scene.activeCamera.position.clone();
  86149. }
  86150. if (this._deviceOrientationCamera) {
  86151. this._deviceOrientationCamera.position = this._position;
  86152. this._scene.activeCamera = this._deviceOrientationCamera;
  86153. if (this._canvas) {
  86154. this._scene.activeCamera.attachControl(this._canvas);
  86155. }
  86156. }
  86157. else if (this._existingCamera) {
  86158. this._existingCamera.position = this._position;
  86159. this._scene.activeCamera = this._existingCamera;
  86160. }
  86161. this.updateButtonVisibility();
  86162. if (this._interactionsEnabled) {
  86163. this._scene.unregisterBeforeRender(this.beforeRender);
  86164. }
  86165. };
  86166. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  86167. /**
  86168. * The position of the vr experience helper.
  86169. */
  86170. get: function () {
  86171. return this._position;
  86172. },
  86173. /**
  86174. * Sets the position of the vr experience helper.
  86175. */
  86176. set: function (value) {
  86177. this._position = value;
  86178. if (this._scene.activeCamera) {
  86179. this._scene.activeCamera.position = value;
  86180. }
  86181. },
  86182. enumerable: true,
  86183. configurable: true
  86184. });
  86185. /**
  86186. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  86187. */
  86188. VRExperienceHelper.prototype.enableInteractions = function () {
  86189. var _this = this;
  86190. if (!this._interactionsEnabled) {
  86191. this._interactionsRequested = true;
  86192. if (this.leftController) {
  86193. this._enableInteractionOnController(this.leftController);
  86194. }
  86195. if (this.rightController) {
  86196. this._enableInteractionOnController(this.rightController);
  86197. }
  86198. this.raySelectionPredicate = function (mesh) {
  86199. return mesh.isVisible;
  86200. };
  86201. this.meshSelectionPredicate = function (mesh) {
  86202. return true;
  86203. };
  86204. this._raySelectionPredicate = function (mesh) {
  86205. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  86206. && mesh.name.indexOf("teleportationTarget") === -1
  86207. && mesh.name.indexOf("torusTeleportation") === -1
  86208. && mesh.name.indexOf("laserPointer") === -1)) {
  86209. return _this.raySelectionPredicate(mesh);
  86210. }
  86211. return false;
  86212. };
  86213. this._interactionsEnabled = true;
  86214. }
  86215. };
  86216. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  86217. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  86218. if (this._floorMeshesCollection[i].id === mesh.id) {
  86219. return true;
  86220. }
  86221. }
  86222. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  86223. return true;
  86224. }
  86225. return false;
  86226. };
  86227. /**
  86228. * Adds a floor mesh to be used for teleportation.
  86229. * @param floorMesh the mesh to be used for teleportation.
  86230. */
  86231. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  86232. if (!this._floorMeshesCollection) {
  86233. return;
  86234. }
  86235. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  86236. return;
  86237. }
  86238. this._floorMeshesCollection.push(floorMesh);
  86239. };
  86240. /**
  86241. * Removes a floor mesh from being used for teleportation.
  86242. * @param floorMesh the mesh to be removed.
  86243. */
  86244. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  86245. if (!this._floorMeshesCollection) {
  86246. return;
  86247. }
  86248. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  86249. if (meshIndex !== -1) {
  86250. this._floorMeshesCollection.splice(meshIndex, 1);
  86251. }
  86252. };
  86253. /**
  86254. * Enables interactions and teleportation using the VR controllers and gaze.
  86255. * @param vrTeleportationOptions options to modify teleportation behavior.
  86256. */
  86257. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  86258. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  86259. if (!this._teleportationInitialized) {
  86260. this._teleportationRequested = true;
  86261. this.enableInteractions();
  86262. if (vrTeleportationOptions.floorMeshName) {
  86263. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  86264. }
  86265. if (vrTeleportationOptions.floorMeshes) {
  86266. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  86267. }
  86268. if (this.leftController != null) {
  86269. this._enableTeleportationOnController(this.leftController);
  86270. }
  86271. if (this.rightController != null) {
  86272. this._enableTeleportationOnController(this.rightController);
  86273. }
  86274. // Creates an image processing post process for the vignette not relying
  86275. // on the main scene configuration for image processing to reduce setup and spaces
  86276. // (gamma/linear) conflicts.
  86277. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  86278. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  86279. imageProcessingConfiguration.vignetteEnabled = true;
  86280. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  86281. this._webVRCamera.detachPostProcess(this._postProcessMove);
  86282. this._teleportationInitialized = true;
  86283. if (this._isDefaultTeleportationTarget) {
  86284. this._createTeleportationCircles();
  86285. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  86286. }
  86287. }
  86288. };
  86289. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  86290. var _this = this;
  86291. var controllerMesh = controller.webVRController.mesh;
  86292. if (controllerMesh) {
  86293. controller._interactionsEnabled = true;
  86294. controller._activatePointer();
  86295. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  86296. // Enabling / disabling laserPointer
  86297. if (_this._displayLaserPointer && stateObject.value === 1) {
  86298. if (controller._activePointer) {
  86299. controller._deactivatePointer();
  86300. }
  86301. else {
  86302. controller._activatePointer();
  86303. }
  86304. if (_this.displayGaze) {
  86305. controller._gazeTracker.isVisible = controller._activePointer;
  86306. }
  86307. }
  86308. });
  86309. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  86310. if (!controller._pointerDownOnMeshAsked) {
  86311. if (stateObject.value > _this._padSensibilityUp) {
  86312. controller._selectionPointerDown();
  86313. }
  86314. }
  86315. else if (stateObject.value < _this._padSensibilityDown) {
  86316. controller._selectionPointerUp();
  86317. }
  86318. });
  86319. }
  86320. };
  86321. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  86322. // Dont teleport if another gaze already requested teleportation
  86323. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  86324. return;
  86325. }
  86326. if (!gazer._teleportationRequestInitiated) {
  86327. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  86328. gazer._activatePointer();
  86329. gazer._teleportationRequestInitiated = true;
  86330. }
  86331. }
  86332. else {
  86333. // Listening to the proper controller values changes to confirm teleportation
  86334. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  86335. if (this._teleportActive) {
  86336. this._teleportCamera(this._haloCenter);
  86337. }
  86338. gazer._teleportationRequestInitiated = false;
  86339. }
  86340. }
  86341. };
  86342. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  86343. // Only rotate when user is not currently selecting a teleportation location
  86344. if (gazer._teleportationRequestInitiated) {
  86345. return;
  86346. }
  86347. if (!this._rotationLeftAsked) {
  86348. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  86349. this._rotationLeftAsked = true;
  86350. if (this._rotationAllowed) {
  86351. this._rotateCamera(false);
  86352. }
  86353. }
  86354. }
  86355. else {
  86356. if (stateObject.x > -this._padSensibilityDown) {
  86357. this._rotationLeftAsked = false;
  86358. }
  86359. }
  86360. if (!this._rotationRightAsked) {
  86361. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  86362. this._rotationRightAsked = true;
  86363. if (this._rotationAllowed) {
  86364. this._rotateCamera(true);
  86365. }
  86366. }
  86367. }
  86368. else {
  86369. if (stateObject.x < this._padSensibilityDown) {
  86370. this._rotationRightAsked = false;
  86371. }
  86372. }
  86373. };
  86374. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  86375. // Only teleport backwards when user is not currently selecting a teleportation location
  86376. if (gazer._teleportationRequestInitiated) {
  86377. return;
  86378. }
  86379. // Teleport backwards
  86380. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  86381. if (!gazer._teleportationBackRequestInitiated) {
  86382. if (!this.currentVRCamera) {
  86383. return;
  86384. }
  86385. // Get rotation and position of the current camera
  86386. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  86387. var position = this.currentVRCamera.position;
  86388. // If the camera has device position, use that instead
  86389. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  86390. rotation = this.currentVRCamera.deviceRotationQuaternion;
  86391. position = this.currentVRCamera.devicePosition;
  86392. }
  86393. // Get matrix with only the y rotation of the device rotation
  86394. rotation.toEulerAnglesToRef(this._workingVector);
  86395. this._workingVector.z = 0;
  86396. this._workingVector.x = 0;
  86397. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  86398. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  86399. // Rotate backwards ray by device rotation to cast at the ground behind the user
  86400. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  86401. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  86402. var ray = new BABYLON.Ray(position, this._workingVector);
  86403. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  86404. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  86405. this._teleportCamera(hit.pickedPoint);
  86406. }
  86407. gazer._teleportationBackRequestInitiated = true;
  86408. }
  86409. }
  86410. else {
  86411. gazer._teleportationBackRequestInitiated = false;
  86412. }
  86413. };
  86414. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  86415. var _this = this;
  86416. var controllerMesh = controller.webVRController.mesh;
  86417. if (controllerMesh) {
  86418. if (!controller._interactionsEnabled) {
  86419. this._enableInteractionOnController(controller);
  86420. }
  86421. controller._interactionsEnabled = true;
  86422. controller._teleportationEnabled = true;
  86423. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86424. controller._dpadPressed = false;
  86425. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  86426. controller._dpadPressed = stateObject.pressed;
  86427. if (!controller._dpadPressed) {
  86428. _this._rotationLeftAsked = false;
  86429. _this._rotationRightAsked = false;
  86430. controller._teleportationBackRequestInitiated = false;
  86431. }
  86432. });
  86433. }
  86434. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  86435. if (_this.teleportationEnabled) {
  86436. _this._checkTeleportBackwards(stateObject, controller);
  86437. _this._checkTeleportWithRay(stateObject, controller);
  86438. }
  86439. _this._checkRotate(stateObject, controller);
  86440. });
  86441. }
  86442. };
  86443. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  86444. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  86445. this._teleportationTarget.isPickable = false;
  86446. var length = 512;
  86447. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  86448. dynamicTexture.hasAlpha = true;
  86449. var context = dynamicTexture.getContext();
  86450. var centerX = length / 2;
  86451. var centerY = length / 2;
  86452. var radius = 200;
  86453. context.beginPath();
  86454. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  86455. context.fillStyle = this._teleportationFillColor;
  86456. context.fill();
  86457. context.lineWidth = 10;
  86458. context.strokeStyle = this._teleportationBorderColor;
  86459. context.stroke();
  86460. context.closePath();
  86461. dynamicTexture.update();
  86462. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  86463. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  86464. this._teleportationTarget.material = teleportationCircleMaterial;
  86465. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  86466. torus.isPickable = false;
  86467. torus.parent = this._teleportationTarget;
  86468. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  86469. var keys = [];
  86470. keys.push({
  86471. frame: 0,
  86472. value: 0
  86473. });
  86474. keys.push({
  86475. frame: 30,
  86476. value: 0.4
  86477. });
  86478. keys.push({
  86479. frame: 60,
  86480. value: 0
  86481. });
  86482. animationInnerCircle.setKeys(keys);
  86483. var easingFunction = new BABYLON.SineEase();
  86484. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  86485. animationInnerCircle.setEasingFunction(easingFunction);
  86486. torus.animations = [];
  86487. torus.animations.push(animationInnerCircle);
  86488. this._scene.beginAnimation(torus, 0, 60, true);
  86489. this._hideTeleportationTarget();
  86490. };
  86491. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  86492. this._teleportActive = true;
  86493. if (this._teleportationInitialized) {
  86494. this._teleportationTarget.isVisible = true;
  86495. if (this._isDefaultTeleportationTarget) {
  86496. this._teleportationTarget.getChildren()[0].isVisible = true;
  86497. }
  86498. }
  86499. };
  86500. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  86501. this._teleportActive = false;
  86502. if (this._teleportationInitialized) {
  86503. this._teleportationTarget.isVisible = false;
  86504. if (this._isDefaultTeleportationTarget) {
  86505. this._teleportationTarget.getChildren()[0].isVisible = false;
  86506. }
  86507. }
  86508. };
  86509. VRExperienceHelper.prototype._rotateCamera = function (right) {
  86510. var _this = this;
  86511. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86512. return;
  86513. }
  86514. if (right) {
  86515. this._rotationAngle++;
  86516. }
  86517. else {
  86518. this._rotationAngle--;
  86519. }
  86520. this.currentVRCamera.animations = [];
  86521. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  86522. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86523. var animationRotationKeys = [];
  86524. animationRotationKeys.push({
  86525. frame: 0,
  86526. value: this.currentVRCamera.rotationQuaternion
  86527. });
  86528. animationRotationKeys.push({
  86529. frame: 6,
  86530. value: target
  86531. });
  86532. animationRotation.setKeys(animationRotationKeys);
  86533. animationRotation.setEasingFunction(this._circleEase);
  86534. this.currentVRCamera.animations.push(animationRotation);
  86535. this._postProcessMove.animations = [];
  86536. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86537. var vignetteWeightKeys = [];
  86538. vignetteWeightKeys.push({
  86539. frame: 0,
  86540. value: 0
  86541. });
  86542. vignetteWeightKeys.push({
  86543. frame: 3,
  86544. value: 4
  86545. });
  86546. vignetteWeightKeys.push({
  86547. frame: 6,
  86548. value: 0
  86549. });
  86550. animationPP.setKeys(vignetteWeightKeys);
  86551. animationPP.setEasingFunction(this._circleEase);
  86552. this._postProcessMove.animations.push(animationPP);
  86553. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86554. var vignetteStretchKeys = [];
  86555. vignetteStretchKeys.push({
  86556. frame: 0,
  86557. value: 0
  86558. });
  86559. vignetteStretchKeys.push({
  86560. frame: 3,
  86561. value: 10
  86562. });
  86563. vignetteStretchKeys.push({
  86564. frame: 6,
  86565. value: 0
  86566. });
  86567. animationPP2.setKeys(vignetteStretchKeys);
  86568. animationPP2.setEasingFunction(this._circleEase);
  86569. this._postProcessMove.animations.push(animationPP2);
  86570. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  86571. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  86572. this._postProcessMove.samples = 4;
  86573. this._webVRCamera.attachPostProcess(this._postProcessMove);
  86574. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  86575. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  86576. });
  86577. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  86578. };
  86579. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  86580. if (hit.pickedPoint) {
  86581. if (gazer._teleportationRequestInitiated) {
  86582. this._displayTeleportationTarget();
  86583. this._haloCenter.copyFrom(hit.pickedPoint);
  86584. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  86585. }
  86586. var pickNormal = hit.getNormal(true, false);
  86587. if (pickNormal) {
  86588. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  86589. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  86590. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  86591. }
  86592. this._teleportationTarget.position.y += 0.1;
  86593. }
  86594. };
  86595. VRExperienceHelper.prototype._teleportCamera = function (location) {
  86596. var _this = this;
  86597. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86598. return;
  86599. }
  86600. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  86601. // offset of the headset from the anchor.
  86602. if (this.webVRCamera.leftCamera) {
  86603. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  86604. this._workingVector.subtractInPlace(this.webVRCamera.position);
  86605. location.subtractToRef(this._workingVector, this._workingVector);
  86606. }
  86607. else {
  86608. this._workingVector.copyFrom(location);
  86609. }
  86610. // Add height to account for user's height offset
  86611. if (this.isInVRMode) {
  86612. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  86613. }
  86614. else {
  86615. this._workingVector.y += this._defaultHeight;
  86616. }
  86617. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  86618. // Create animation from the camera's position to the new location
  86619. this.currentVRCamera.animations = [];
  86620. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86621. var animationCameraTeleportationKeys = [{
  86622. frame: 0,
  86623. value: this.currentVRCamera.position
  86624. },
  86625. {
  86626. frame: 11,
  86627. value: this._workingVector
  86628. }
  86629. ];
  86630. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  86631. animationCameraTeleportation.setEasingFunction(this._circleEase);
  86632. this.currentVRCamera.animations.push(animationCameraTeleportation);
  86633. this._postProcessMove.animations = [];
  86634. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86635. var vignetteWeightKeys = [];
  86636. vignetteWeightKeys.push({
  86637. frame: 0,
  86638. value: 0
  86639. });
  86640. vignetteWeightKeys.push({
  86641. frame: 5,
  86642. value: 8
  86643. });
  86644. vignetteWeightKeys.push({
  86645. frame: 11,
  86646. value: 0
  86647. });
  86648. animationPP.setKeys(vignetteWeightKeys);
  86649. this._postProcessMove.animations.push(animationPP);
  86650. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86651. var vignetteStretchKeys = [];
  86652. vignetteStretchKeys.push({
  86653. frame: 0,
  86654. value: 0
  86655. });
  86656. vignetteStretchKeys.push({
  86657. frame: 5,
  86658. value: 10
  86659. });
  86660. vignetteStretchKeys.push({
  86661. frame: 11,
  86662. value: 0
  86663. });
  86664. animationPP2.setKeys(vignetteStretchKeys);
  86665. this._postProcessMove.animations.push(animationPP2);
  86666. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  86667. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  86668. this._webVRCamera.attachPostProcess(this._postProcessMove);
  86669. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  86670. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  86671. });
  86672. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  86673. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  86674. });
  86675. this._hideTeleportationTarget();
  86676. };
  86677. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  86678. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86679. return;
  86680. }
  86681. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  86682. // Moving the gazeTracker on the mesh face targetted
  86683. if (hit && hit.pickedPoint) {
  86684. if (this._displayGaze) {
  86685. var multiplier = 1;
  86686. gazer._gazeTracker.isVisible = true;
  86687. if (gazer._isActionableMesh) {
  86688. multiplier = 3;
  86689. }
  86690. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  86691. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  86692. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  86693. var pickNormal = hit.getNormal();
  86694. // To avoid z-fighting
  86695. var deltaFighting = 0.002;
  86696. if (pickNormal) {
  86697. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  86698. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  86699. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  86700. }
  86701. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  86702. if (gazer._gazeTracker.position.x < 0) {
  86703. gazer._gazeTracker.position.x += deltaFighting;
  86704. }
  86705. else {
  86706. gazer._gazeTracker.position.x -= deltaFighting;
  86707. }
  86708. if (gazer._gazeTracker.position.y < 0) {
  86709. gazer._gazeTracker.position.y += deltaFighting;
  86710. }
  86711. else {
  86712. gazer._gazeTracker.position.y -= deltaFighting;
  86713. }
  86714. if (gazer._gazeTracker.position.z < 0) {
  86715. gazer._gazeTracker.position.z += deltaFighting;
  86716. }
  86717. else {
  86718. gazer._gazeTracker.position.z -= deltaFighting;
  86719. }
  86720. }
  86721. // Changing the size of the laser pointer based on the distance from the targetted point
  86722. gazer._updatePointerDistance(hit.distance);
  86723. }
  86724. else {
  86725. gazer._gazeTracker.isVisible = false;
  86726. }
  86727. if (hit && hit.pickedMesh) {
  86728. gazer._currentHit = hit;
  86729. if (gazer._pointerDownOnMeshAsked) {
  86730. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  86731. }
  86732. // The object selected is the floor, we're in a teleportation scenario
  86733. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  86734. // Moving the teleportation area to this targetted point
  86735. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  86736. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  86737. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86738. }
  86739. gazer._currentMeshSelected = null;
  86740. if (gazer._teleportationRequestInitiated) {
  86741. this._moveTeleportationSelectorTo(hit, gazer);
  86742. }
  86743. return;
  86744. }
  86745. // If not, we're in a selection scenario
  86746. //this._teleportationAllowed = false;
  86747. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  86748. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  86749. this.onNewMeshPicked.notifyObservers(hit);
  86750. gazer._currentMeshSelected = hit.pickedMesh;
  86751. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  86752. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  86753. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  86754. gazer._isActionableMesh = true;
  86755. }
  86756. else {
  86757. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86758. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86759. gazer._isActionableMesh = false;
  86760. }
  86761. try {
  86762. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  86763. }
  86764. catch (err) {
  86765. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  86766. }
  86767. }
  86768. else {
  86769. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86770. gazer._currentMeshSelected = null;
  86771. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86772. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86773. }
  86774. }
  86775. }
  86776. else {
  86777. gazer._currentHit = null;
  86778. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86779. gazer._currentMeshSelected = null;
  86780. //this._teleportationAllowed = false;
  86781. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86782. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86783. }
  86784. };
  86785. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  86786. if (mesh) {
  86787. this.onSelectedMeshUnselected.notifyObservers(mesh);
  86788. }
  86789. };
  86790. /**
  86791. * Sets the color of the laser ray from the vr controllers.
  86792. * @param color new color for the ray.
  86793. */
  86794. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  86795. if (this.leftController) {
  86796. this.leftController._setLaserPointerColor(color);
  86797. }
  86798. if (this.rightController) {
  86799. this.rightController._setLaserPointerColor(color);
  86800. }
  86801. };
  86802. /**
  86803. * Sets the color of the ray from the vr headsets gaze.
  86804. * @param color new color for the ray.
  86805. */
  86806. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  86807. if (!this._cameraGazer._gazeTracker.material) {
  86808. return;
  86809. }
  86810. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  86811. if (this.leftController) {
  86812. this.leftController._gazeTracker.material.emissiveColor = color;
  86813. }
  86814. if (this.rightController) {
  86815. this.rightController._gazeTracker.material.emissiveColor = color;
  86816. }
  86817. };
  86818. /**
  86819. * Exits VR and disposes of the vr experience helper
  86820. */
  86821. VRExperienceHelper.prototype.dispose = function () {
  86822. if (this.isInVRMode) {
  86823. this.exitVR();
  86824. }
  86825. if (this._postProcessMove) {
  86826. this._postProcessMove.dispose();
  86827. }
  86828. if (this._webVRCamera) {
  86829. this._webVRCamera.dispose();
  86830. }
  86831. if (this._vrDeviceOrientationCamera) {
  86832. this._vrDeviceOrientationCamera.dispose();
  86833. }
  86834. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  86835. document.body.removeChild(this._btnVR);
  86836. }
  86837. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  86838. this._deviceOrientationCamera.dispose();
  86839. }
  86840. if (this._cameraGazer) {
  86841. this._cameraGazer.dispose();
  86842. }
  86843. if (this.leftController) {
  86844. this.leftController.dispose();
  86845. }
  86846. if (this.rightController) {
  86847. this.rightController.dispose();
  86848. }
  86849. if (this._teleportationTarget) {
  86850. this._teleportationTarget.dispose();
  86851. }
  86852. this._floorMeshesCollection = [];
  86853. document.removeEventListener("keydown", this._onKeyDown);
  86854. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86855. window.removeEventListener("resize", this._onResize);
  86856. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  86857. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  86858. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  86859. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  86860. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  86861. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  86862. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  86863. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86864. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  86865. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  86866. this._scene.unregisterBeforeRender(this.beforeRender);
  86867. };
  86868. /**
  86869. * Gets the name of the VRExperienceHelper class
  86870. * @returns "VRExperienceHelper"
  86871. */
  86872. VRExperienceHelper.prototype.getClassName = function () {
  86873. return "VRExperienceHelper";
  86874. };
  86875. return VRExperienceHelper;
  86876. }());
  86877. BABYLON.VRExperienceHelper = VRExperienceHelper;
  86878. })(BABYLON || (BABYLON = {}));
  86879. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  86880. "use strict";
  86881. // Mainly based on these 2 articles :
  86882. // 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
  86883. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  86884. var BABYLON;
  86885. (function (BABYLON) {
  86886. var JoystickAxis;
  86887. (function (JoystickAxis) {
  86888. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  86889. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  86890. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  86891. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  86892. var VirtualJoystick = /** @class */ (function () {
  86893. function VirtualJoystick(leftJoystick) {
  86894. var _this = this;
  86895. if (leftJoystick) {
  86896. this._leftJoystick = true;
  86897. }
  86898. else {
  86899. this._leftJoystick = false;
  86900. }
  86901. VirtualJoystick._globalJoystickIndex++;
  86902. // By default left & right arrow keys are moving the X
  86903. // and up & down keys are moving the Y
  86904. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  86905. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  86906. this.reverseLeftRight = false;
  86907. this.reverseUpDown = false;
  86908. // collections of pointers
  86909. this._touches = new BABYLON.StringDictionary();
  86910. this.deltaPosition = BABYLON.Vector3.Zero();
  86911. this._joystickSensibility = 25;
  86912. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  86913. this._onResize = function (evt) {
  86914. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  86915. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  86916. if (VirtualJoystick.vjCanvas) {
  86917. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  86918. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  86919. }
  86920. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  86921. };
  86922. // injecting a canvas element on top of the canvas 3D game
  86923. if (!VirtualJoystick.vjCanvas) {
  86924. window.addEventListener("resize", this._onResize, false);
  86925. VirtualJoystick.vjCanvas = document.createElement("canvas");
  86926. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  86927. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  86928. VirtualJoystick.vjCanvas.width = window.innerWidth;
  86929. VirtualJoystick.vjCanvas.height = window.innerHeight;
  86930. VirtualJoystick.vjCanvas.style.width = "100%";
  86931. VirtualJoystick.vjCanvas.style.height = "100%";
  86932. VirtualJoystick.vjCanvas.style.position = "absolute";
  86933. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  86934. VirtualJoystick.vjCanvas.style.top = "0px";
  86935. VirtualJoystick.vjCanvas.style.left = "0px";
  86936. VirtualJoystick.vjCanvas.style.zIndex = "5";
  86937. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  86938. // Support for jQuery PEP polyfill
  86939. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  86940. var context = VirtualJoystick.vjCanvas.getContext('2d');
  86941. if (!context) {
  86942. throw new Error("Unable to create canvas for virtual joystick");
  86943. }
  86944. VirtualJoystick.vjCanvasContext = context;
  86945. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  86946. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  86947. document.body.appendChild(VirtualJoystick.vjCanvas);
  86948. }
  86949. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  86950. this.pressed = false;
  86951. // default joystick color
  86952. this._joystickColor = "cyan";
  86953. this._joystickPointerID = -1;
  86954. // current joystick position
  86955. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  86956. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  86957. // origin joystick position
  86958. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  86959. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  86960. this._onPointerDownHandlerRef = function (evt) {
  86961. _this._onPointerDown(evt);
  86962. };
  86963. this._onPointerMoveHandlerRef = function (evt) {
  86964. _this._onPointerMove(evt);
  86965. };
  86966. this._onPointerUpHandlerRef = function (evt) {
  86967. _this._onPointerUp(evt);
  86968. };
  86969. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  86970. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  86971. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  86972. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  86973. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  86974. evt.preventDefault(); // Disables system menu
  86975. }, false);
  86976. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  86977. }
  86978. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  86979. this._joystickSensibility = newJoystickSensibility;
  86980. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  86981. };
  86982. VirtualJoystick.prototype._onPointerDown = function (e) {
  86983. var positionOnScreenCondition;
  86984. e.preventDefault();
  86985. if (this._leftJoystick === true) {
  86986. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  86987. }
  86988. else {
  86989. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  86990. }
  86991. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  86992. // First contact will be dedicated to the virtual joystick
  86993. this._joystickPointerID = e.pointerId;
  86994. this._joystickPointerStartPos.x = e.clientX;
  86995. this._joystickPointerStartPos.y = e.clientY;
  86996. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  86997. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  86998. this._deltaJoystickVector.x = 0;
  86999. this._deltaJoystickVector.y = 0;
  87000. this.pressed = true;
  87001. this._touches.add(e.pointerId.toString(), e);
  87002. }
  87003. else {
  87004. // You can only trigger the action buttons with a joystick declared
  87005. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  87006. this._action();
  87007. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  87008. }
  87009. }
  87010. };
  87011. VirtualJoystick.prototype._onPointerMove = function (e) {
  87012. // If the current pointer is the one associated to the joystick (first touch contact)
  87013. if (this._joystickPointerID == e.pointerId) {
  87014. this._joystickPointerPos.x = e.clientX;
  87015. this._joystickPointerPos.y = e.clientY;
  87016. this._deltaJoystickVector = this._joystickPointerPos.clone();
  87017. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  87018. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  87019. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  87020. switch (this._axisTargetedByLeftAndRight) {
  87021. case JoystickAxis.X:
  87022. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  87023. break;
  87024. case JoystickAxis.Y:
  87025. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  87026. break;
  87027. case JoystickAxis.Z:
  87028. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  87029. break;
  87030. }
  87031. var directionUpDown = this.reverseUpDown ? 1 : -1;
  87032. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  87033. switch (this._axisTargetedByUpAndDown) {
  87034. case JoystickAxis.X:
  87035. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  87036. break;
  87037. case JoystickAxis.Y:
  87038. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  87039. break;
  87040. case JoystickAxis.Z:
  87041. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  87042. break;
  87043. }
  87044. }
  87045. else {
  87046. var data = this._touches.get(e.pointerId.toString());
  87047. if (data) {
  87048. data.x = e.clientX;
  87049. data.y = e.clientY;
  87050. }
  87051. }
  87052. };
  87053. VirtualJoystick.prototype._onPointerUp = function (e) {
  87054. if (this._joystickPointerID == e.pointerId) {
  87055. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  87056. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  87057. this._joystickPointerID = -1;
  87058. this.pressed = false;
  87059. }
  87060. else {
  87061. var touch = this._touches.get(e.pointerId.toString());
  87062. if (touch) {
  87063. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  87064. }
  87065. }
  87066. this._deltaJoystickVector.x = 0;
  87067. this._deltaJoystickVector.y = 0;
  87068. this._touches.remove(e.pointerId.toString());
  87069. };
  87070. /**
  87071. * Change the color of the virtual joystick
  87072. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  87073. */
  87074. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  87075. this._joystickColor = newColor;
  87076. };
  87077. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  87078. this._action = action;
  87079. };
  87080. // Define which axis you'd like to control for left & right
  87081. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  87082. switch (axis) {
  87083. case JoystickAxis.X:
  87084. case JoystickAxis.Y:
  87085. case JoystickAxis.Z:
  87086. this._axisTargetedByLeftAndRight = axis;
  87087. break;
  87088. default:
  87089. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  87090. break;
  87091. }
  87092. };
  87093. // Define which axis you'd like to control for up & down
  87094. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  87095. switch (axis) {
  87096. case JoystickAxis.X:
  87097. case JoystickAxis.Y:
  87098. case JoystickAxis.Z:
  87099. this._axisTargetedByUpAndDown = axis;
  87100. break;
  87101. default:
  87102. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  87103. break;
  87104. }
  87105. };
  87106. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  87107. var _this = this;
  87108. if (this.pressed) {
  87109. this._touches.forEach(function (key, touch) {
  87110. if (touch.pointerId === _this._joystickPointerID) {
  87111. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  87112. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  87113. VirtualJoystick.vjCanvasContext.beginPath();
  87114. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  87115. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87116. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  87117. VirtualJoystick.vjCanvasContext.stroke();
  87118. VirtualJoystick.vjCanvasContext.closePath();
  87119. VirtualJoystick.vjCanvasContext.beginPath();
  87120. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87121. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  87122. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  87123. VirtualJoystick.vjCanvasContext.stroke();
  87124. VirtualJoystick.vjCanvasContext.closePath();
  87125. VirtualJoystick.vjCanvasContext.beginPath();
  87126. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87127. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  87128. VirtualJoystick.vjCanvasContext.stroke();
  87129. VirtualJoystick.vjCanvasContext.closePath();
  87130. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  87131. }
  87132. else {
  87133. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  87134. VirtualJoystick.vjCanvasContext.beginPath();
  87135. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  87136. VirtualJoystick.vjCanvasContext.beginPath();
  87137. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  87138. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  87139. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  87140. VirtualJoystick.vjCanvasContext.stroke();
  87141. VirtualJoystick.vjCanvasContext.closePath();
  87142. touch.prevX = touch.x;
  87143. touch.prevY = touch.y;
  87144. }
  87145. ;
  87146. });
  87147. }
  87148. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  87149. };
  87150. VirtualJoystick.prototype.releaseCanvas = function () {
  87151. if (VirtualJoystick.vjCanvas) {
  87152. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  87153. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  87154. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  87155. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  87156. window.removeEventListener("resize", this._onResize);
  87157. document.body.removeChild(VirtualJoystick.vjCanvas);
  87158. VirtualJoystick.vjCanvas = null;
  87159. }
  87160. };
  87161. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  87162. VirtualJoystick._globalJoystickIndex = 0;
  87163. return VirtualJoystick;
  87164. }());
  87165. BABYLON.VirtualJoystick = VirtualJoystick;
  87166. })(BABYLON || (BABYLON = {}));
  87167. //# sourceMappingURL=babylon.virtualJoystick.js.map
  87168. "use strict";
  87169. var BABYLON;
  87170. (function (BABYLON) {
  87171. // We're mainly based on the logic defined into the FreeCamera code
  87172. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  87173. __extends(VirtualJoysticksCamera, _super);
  87174. function VirtualJoysticksCamera(name, position, scene) {
  87175. var _this = _super.call(this, name, position, scene) || this;
  87176. _this.inputs.addVirtualJoystick();
  87177. return _this;
  87178. }
  87179. VirtualJoysticksCamera.prototype.getClassName = function () {
  87180. return "VirtualJoysticksCamera";
  87181. };
  87182. return VirtualJoysticksCamera;
  87183. }(BABYLON.FreeCamera));
  87184. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  87185. })(BABYLON || (BABYLON = {}));
  87186. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  87187. "use strict";
  87188. var BABYLON;
  87189. (function (BABYLON) {
  87190. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  87191. function FreeCameraVirtualJoystickInput() {
  87192. }
  87193. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  87194. return this._leftjoystick;
  87195. };
  87196. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  87197. return this._rightjoystick;
  87198. };
  87199. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  87200. if (this._leftjoystick) {
  87201. var camera = this.camera;
  87202. var speed = camera._computeLocalCameraSpeed() * 50;
  87203. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  87204. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  87205. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  87206. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  87207. if (!this._leftjoystick.pressed) {
  87208. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  87209. }
  87210. if (!this._rightjoystick.pressed) {
  87211. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  87212. }
  87213. }
  87214. };
  87215. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  87216. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  87217. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  87218. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  87219. this._leftjoystick.setJoystickSensibility(0.15);
  87220. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  87221. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  87222. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  87223. this._rightjoystick.reverseUpDown = true;
  87224. this._rightjoystick.setJoystickSensibility(0.05);
  87225. this._rightjoystick.setJoystickColor("yellow");
  87226. };
  87227. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  87228. this._leftjoystick.releaseCanvas();
  87229. this._rightjoystick.releaseCanvas();
  87230. };
  87231. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  87232. return "FreeCameraVirtualJoystickInput";
  87233. };
  87234. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  87235. return "virtualJoystick";
  87236. };
  87237. return FreeCameraVirtualJoystickInput;
  87238. }());
  87239. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  87240. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  87241. })(BABYLON || (BABYLON = {}));
  87242. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  87243. "use strict";
  87244. var BABYLON;
  87245. (function (BABYLON) {
  87246. var SimplificationSettings = /** @class */ (function () {
  87247. function SimplificationSettings(quality, distance, optimizeMesh) {
  87248. this.quality = quality;
  87249. this.distance = distance;
  87250. this.optimizeMesh = optimizeMesh;
  87251. }
  87252. return SimplificationSettings;
  87253. }());
  87254. BABYLON.SimplificationSettings = SimplificationSettings;
  87255. var SimplificationQueue = /** @class */ (function () {
  87256. function SimplificationQueue() {
  87257. this.running = false;
  87258. this._simplificationArray = [];
  87259. }
  87260. SimplificationQueue.prototype.addTask = function (task) {
  87261. this._simplificationArray.push(task);
  87262. };
  87263. SimplificationQueue.prototype.executeNext = function () {
  87264. var task = this._simplificationArray.pop();
  87265. if (task) {
  87266. this.running = true;
  87267. this.runSimplification(task);
  87268. }
  87269. else {
  87270. this.running = false;
  87271. }
  87272. };
  87273. SimplificationQueue.prototype.runSimplification = function (task) {
  87274. var _this = this;
  87275. if (task.parallelProcessing) {
  87276. //parallel simplifier
  87277. task.settings.forEach(function (setting) {
  87278. var simplifier = _this.getSimplifier(task);
  87279. simplifier.simplify(setting, function (newMesh) {
  87280. task.mesh.addLODLevel(setting.distance, newMesh);
  87281. newMesh.isVisible = true;
  87282. //check if it is the last
  87283. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  87284. //all done, run the success callback.
  87285. task.successCallback();
  87286. }
  87287. _this.executeNext();
  87288. });
  87289. });
  87290. }
  87291. else {
  87292. //single simplifier.
  87293. var simplifier = this.getSimplifier(task);
  87294. var runDecimation = function (setting, callback) {
  87295. simplifier.simplify(setting, function (newMesh) {
  87296. task.mesh.addLODLevel(setting.distance, newMesh);
  87297. newMesh.isVisible = true;
  87298. //run the next quality level
  87299. callback();
  87300. });
  87301. };
  87302. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  87303. runDecimation(task.settings[loop.index], function () {
  87304. loop.executeNext();
  87305. });
  87306. }, function () {
  87307. //execution ended, run the success callback.
  87308. if (task.successCallback) {
  87309. task.successCallback();
  87310. }
  87311. _this.executeNext();
  87312. });
  87313. }
  87314. };
  87315. SimplificationQueue.prototype.getSimplifier = function (task) {
  87316. switch (task.simplificationType) {
  87317. case SimplificationType.QUADRATIC:
  87318. default:
  87319. return new QuadraticErrorSimplification(task.mesh);
  87320. }
  87321. };
  87322. return SimplificationQueue;
  87323. }());
  87324. BABYLON.SimplificationQueue = SimplificationQueue;
  87325. /**
  87326. * The implemented types of simplification.
  87327. * At the moment only Quadratic Error Decimation is implemented.
  87328. */
  87329. var SimplificationType;
  87330. (function (SimplificationType) {
  87331. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  87332. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  87333. var DecimationTriangle = /** @class */ (function () {
  87334. function DecimationTriangle(vertices) {
  87335. this.vertices = vertices;
  87336. this.error = new Array(4);
  87337. this.deleted = false;
  87338. this.isDirty = false;
  87339. this.deletePending = false;
  87340. this.borderFactor = 0;
  87341. }
  87342. return DecimationTriangle;
  87343. }());
  87344. BABYLON.DecimationTriangle = DecimationTriangle;
  87345. var DecimationVertex = /** @class */ (function () {
  87346. function DecimationVertex(position, id) {
  87347. this.position = position;
  87348. this.id = id;
  87349. this.isBorder = true;
  87350. this.q = new QuadraticMatrix();
  87351. this.triangleCount = 0;
  87352. this.triangleStart = 0;
  87353. this.originalOffsets = [];
  87354. }
  87355. DecimationVertex.prototype.updatePosition = function (newPosition) {
  87356. this.position.copyFrom(newPosition);
  87357. };
  87358. return DecimationVertex;
  87359. }());
  87360. BABYLON.DecimationVertex = DecimationVertex;
  87361. var QuadraticMatrix = /** @class */ (function () {
  87362. function QuadraticMatrix(data) {
  87363. this.data = new Array(10);
  87364. for (var i = 0; i < 10; ++i) {
  87365. if (data && data[i]) {
  87366. this.data[i] = data[i];
  87367. }
  87368. else {
  87369. this.data[i] = 0;
  87370. }
  87371. }
  87372. }
  87373. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  87374. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  87375. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  87376. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  87377. return det;
  87378. };
  87379. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  87380. for (var i = 0; i < 10; ++i) {
  87381. this.data[i] += matrix.data[i];
  87382. }
  87383. };
  87384. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  87385. for (var i = 0; i < 10; ++i) {
  87386. this.data[i] += data[i];
  87387. }
  87388. };
  87389. QuadraticMatrix.prototype.add = function (matrix) {
  87390. var m = new QuadraticMatrix();
  87391. for (var i = 0; i < 10; ++i) {
  87392. m.data[i] = this.data[i] + matrix.data[i];
  87393. }
  87394. return m;
  87395. };
  87396. QuadraticMatrix.FromData = function (a, b, c, d) {
  87397. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  87398. };
  87399. //returning an array to avoid garbage collection
  87400. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  87401. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  87402. };
  87403. return QuadraticMatrix;
  87404. }());
  87405. BABYLON.QuadraticMatrix = QuadraticMatrix;
  87406. var Reference = /** @class */ (function () {
  87407. function Reference(vertexId, triangleId) {
  87408. this.vertexId = vertexId;
  87409. this.triangleId = triangleId;
  87410. }
  87411. return Reference;
  87412. }());
  87413. BABYLON.Reference = Reference;
  87414. /**
  87415. * An implementation of the Quadratic Error simplification algorithm.
  87416. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  87417. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  87418. * @author RaananW
  87419. */
  87420. var QuadraticErrorSimplification = /** @class */ (function () {
  87421. function QuadraticErrorSimplification(_mesh) {
  87422. this._mesh = _mesh;
  87423. this.syncIterations = 5000;
  87424. this.aggressiveness = 7;
  87425. this.decimationIterations = 100;
  87426. this.boundingBoxEpsilon = BABYLON.Epsilon;
  87427. }
  87428. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  87429. var _this = this;
  87430. this.initDecimatedMesh();
  87431. //iterating through the submeshes array, one after the other.
  87432. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  87433. _this.initWithMesh(loop.index, function () {
  87434. _this.runDecimation(settings, loop.index, function () {
  87435. loop.executeNext();
  87436. });
  87437. }, settings.optimizeMesh);
  87438. }, function () {
  87439. setTimeout(function () {
  87440. successCallback(_this._reconstructedMesh);
  87441. }, 0);
  87442. });
  87443. };
  87444. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  87445. var _this = this;
  87446. var targetCount = ~~(this.triangles.length * settings.quality);
  87447. var deletedTriangles = 0;
  87448. var triangleCount = this.triangles.length;
  87449. var iterationFunction = function (iteration, callback) {
  87450. setTimeout(function () {
  87451. if (iteration % 5 === 0) {
  87452. _this.updateMesh(iteration === 0);
  87453. }
  87454. for (var i = 0; i < _this.triangles.length; ++i) {
  87455. _this.triangles[i].isDirty = false;
  87456. }
  87457. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  87458. var trianglesIterator = function (i) {
  87459. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  87460. var t = _this.triangles[tIdx];
  87461. if (!t)
  87462. return;
  87463. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  87464. return;
  87465. }
  87466. for (var j = 0; j < 3; ++j) {
  87467. if (t.error[j] < threshold) {
  87468. var deleted0 = [];
  87469. var deleted1 = [];
  87470. var v0 = t.vertices[j];
  87471. var v1 = t.vertices[(j + 1) % 3];
  87472. if (v0.isBorder || v1.isBorder)
  87473. continue;
  87474. var p = BABYLON.Vector3.Zero();
  87475. var n = BABYLON.Vector3.Zero();
  87476. var uv = BABYLON.Vector2.Zero();
  87477. var color = new BABYLON.Color4(0, 0, 0, 1);
  87478. _this.calculateError(v0, v1, p, n, uv, color);
  87479. var delTr = new Array();
  87480. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  87481. continue;
  87482. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  87483. continue;
  87484. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  87485. continue;
  87486. var uniqueArray = new Array();
  87487. delTr.forEach(function (deletedT) {
  87488. if (uniqueArray.indexOf(deletedT) === -1) {
  87489. deletedT.deletePending = true;
  87490. uniqueArray.push(deletedT);
  87491. }
  87492. });
  87493. if (uniqueArray.length % 2 !== 0) {
  87494. continue;
  87495. }
  87496. v0.q = v1.q.add(v0.q);
  87497. v0.updatePosition(p);
  87498. var tStart = _this.references.length;
  87499. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  87500. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  87501. var tCount = _this.references.length - tStart;
  87502. if (tCount <= v0.triangleCount) {
  87503. if (tCount) {
  87504. for (var c = 0; c < tCount; c++) {
  87505. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  87506. }
  87507. }
  87508. }
  87509. else {
  87510. v0.triangleStart = tStart;
  87511. }
  87512. v0.triangleCount = tCount;
  87513. break;
  87514. }
  87515. }
  87516. };
  87517. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  87518. }, 0);
  87519. };
  87520. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  87521. if (triangleCount - deletedTriangles <= targetCount)
  87522. loop.breakLoop();
  87523. else {
  87524. iterationFunction(loop.index, function () {
  87525. loop.executeNext();
  87526. });
  87527. }
  87528. }, function () {
  87529. setTimeout(function () {
  87530. //reconstruct this part of the mesh
  87531. _this.reconstructMesh(submeshIndex);
  87532. successCallback();
  87533. }, 0);
  87534. });
  87535. };
  87536. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  87537. var _this = this;
  87538. this.vertices = [];
  87539. this.triangles = [];
  87540. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  87541. var indices = this._mesh.getIndices();
  87542. var submesh = this._mesh.subMeshes[submeshIndex];
  87543. var findInVertices = function (positionToSearch) {
  87544. if (optimizeMesh) {
  87545. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  87546. if (_this.vertices[ii].position.equals(positionToSearch)) {
  87547. return _this.vertices[ii];
  87548. }
  87549. }
  87550. }
  87551. return null;
  87552. };
  87553. var vertexReferences = [];
  87554. var vertexInit = function (i) {
  87555. if (!positionData) {
  87556. return;
  87557. }
  87558. var offset = i + submesh.verticesStart;
  87559. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  87560. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  87561. vertex.originalOffsets.push(offset);
  87562. if (vertex.id === _this.vertices.length) {
  87563. _this.vertices.push(vertex);
  87564. }
  87565. vertexReferences.push(vertex.id);
  87566. };
  87567. //var totalVertices = mesh.getTotalVertices();
  87568. var totalVertices = submesh.verticesCount;
  87569. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  87570. var indicesInit = function (i) {
  87571. if (!indices) {
  87572. return;
  87573. }
  87574. var offset = (submesh.indexStart / 3) + i;
  87575. var pos = (offset * 3);
  87576. var i0 = indices[pos + 0];
  87577. var i1 = indices[pos + 1];
  87578. var i2 = indices[pos + 2];
  87579. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  87580. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  87581. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  87582. var triangle = new DecimationTriangle([v0, v1, v2]);
  87583. triangle.originalOffset = pos;
  87584. _this.triangles.push(triangle);
  87585. };
  87586. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  87587. _this.init(callback);
  87588. });
  87589. });
  87590. };
  87591. QuadraticErrorSimplification.prototype.init = function (callback) {
  87592. var _this = this;
  87593. var triangleInit1 = function (i) {
  87594. var t = _this.triangles[i];
  87595. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  87596. for (var j = 0; j < 3; j++) {
  87597. 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))));
  87598. }
  87599. };
  87600. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  87601. var triangleInit2 = function (i) {
  87602. var t = _this.triangles[i];
  87603. for (var j = 0; j < 3; ++j) {
  87604. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  87605. }
  87606. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  87607. };
  87608. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  87609. callback();
  87610. });
  87611. });
  87612. };
  87613. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  87614. var newTriangles = [];
  87615. var i;
  87616. for (i = 0; i < this.vertices.length; ++i) {
  87617. this.vertices[i].triangleCount = 0;
  87618. }
  87619. var t;
  87620. var j;
  87621. for (i = 0; i < this.triangles.length; ++i) {
  87622. if (!this.triangles[i].deleted) {
  87623. t = this.triangles[i];
  87624. for (j = 0; j < 3; ++j) {
  87625. t.vertices[j].triangleCount = 1;
  87626. }
  87627. newTriangles.push(t);
  87628. }
  87629. }
  87630. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  87631. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  87632. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  87633. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  87634. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  87635. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  87636. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  87637. var vertexCount = 0;
  87638. for (i = 0; i < this.vertices.length; ++i) {
  87639. var vertex = this.vertices[i];
  87640. vertex.id = vertexCount;
  87641. if (vertex.triangleCount) {
  87642. vertex.originalOffsets.forEach(function (originalOffset) {
  87643. if (!normalData) {
  87644. return;
  87645. }
  87646. newPositionData.push(vertex.position.x);
  87647. newPositionData.push(vertex.position.y);
  87648. newPositionData.push(vertex.position.z);
  87649. newNormalData.push(normalData[originalOffset * 3]);
  87650. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  87651. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  87652. if (uvs && uvs.length) {
  87653. newUVsData.push(uvs[(originalOffset * 2)]);
  87654. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  87655. }
  87656. else if (colorsData && colorsData.length) {
  87657. newColorsData.push(colorsData[(originalOffset * 4)]);
  87658. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  87659. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  87660. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  87661. }
  87662. ++vertexCount;
  87663. });
  87664. }
  87665. }
  87666. var startingIndex = this._reconstructedMesh.getTotalIndices();
  87667. var startingVertex = this._reconstructedMesh.getTotalVertices();
  87668. var submeshesArray = this._reconstructedMesh.subMeshes;
  87669. this._reconstructedMesh.subMeshes = [];
  87670. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  87671. var originalIndices = this._mesh.getIndices();
  87672. for (i = 0; i < newTriangles.length; ++i) {
  87673. t = newTriangles[i]; //now get the new referencing point for each vertex
  87674. [0, 1, 2].forEach(function (idx) {
  87675. var id = originalIndices[t.originalOffset + idx];
  87676. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  87677. if (offset < 0)
  87678. offset = 0;
  87679. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  87680. });
  87681. }
  87682. //overwriting the old vertex buffers and indices.
  87683. this._reconstructedMesh.setIndices(newIndicesArray);
  87684. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  87685. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  87686. if (newUVsData.length > 0)
  87687. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  87688. if (newColorsData.length > 0)
  87689. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  87690. //create submesh
  87691. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  87692. if (submeshIndex > 0) {
  87693. this._reconstructedMesh.subMeshes = [];
  87694. submeshesArray.forEach(function (submesh) {
  87695. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  87696. });
  87697. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  87698. }
  87699. };
  87700. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  87701. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  87702. this._reconstructedMesh.material = this._mesh.material;
  87703. this._reconstructedMesh.parent = this._mesh.parent;
  87704. this._reconstructedMesh.isVisible = false;
  87705. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  87706. };
  87707. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  87708. for (var i = 0; i < vertex1.triangleCount; ++i) {
  87709. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  87710. if (t.deleted)
  87711. continue;
  87712. var s = this.references[vertex1.triangleStart + i].vertexId;
  87713. var v1 = t.vertices[(s + 1) % 3];
  87714. var v2 = t.vertices[(s + 2) % 3];
  87715. if ((v1 === vertex2 || v2 === vertex2)) {
  87716. deletedArray[i] = true;
  87717. delTr.push(t);
  87718. continue;
  87719. }
  87720. var d1 = v1.position.subtract(point);
  87721. d1 = d1.normalize();
  87722. var d2 = v2.position.subtract(point);
  87723. d2 = d2.normalize();
  87724. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  87725. return true;
  87726. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  87727. deletedArray[i] = false;
  87728. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  87729. return true;
  87730. }
  87731. return false;
  87732. };
  87733. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  87734. var newDeleted = deletedTriangles;
  87735. for (var i = 0; i < vertex.triangleCount; ++i) {
  87736. var ref = this.references[vertex.triangleStart + i];
  87737. var t = this.triangles[ref.triangleId];
  87738. if (t.deleted)
  87739. continue;
  87740. if (deletedArray[i] && t.deletePending) {
  87741. t.deleted = true;
  87742. newDeleted++;
  87743. continue;
  87744. }
  87745. t.vertices[ref.vertexId] = origVertex;
  87746. t.isDirty = true;
  87747. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  87748. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  87749. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  87750. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  87751. this.references.push(ref);
  87752. }
  87753. return newDeleted;
  87754. };
  87755. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  87756. for (var i = 0; i < this.vertices.length; ++i) {
  87757. var vCount = [];
  87758. var vId = [];
  87759. var v = this.vertices[i];
  87760. var j;
  87761. for (j = 0; j < v.triangleCount; ++j) {
  87762. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  87763. for (var ii = 0; ii < 3; ii++) {
  87764. var ofs = 0;
  87765. var vv = triangle.vertices[ii];
  87766. while (ofs < vCount.length) {
  87767. if (vId[ofs] === vv.id)
  87768. break;
  87769. ++ofs;
  87770. }
  87771. if (ofs === vCount.length) {
  87772. vCount.push(1);
  87773. vId.push(vv.id);
  87774. }
  87775. else {
  87776. vCount[ofs]++;
  87777. }
  87778. }
  87779. }
  87780. for (j = 0; j < vCount.length; ++j) {
  87781. if (vCount[j] === 1) {
  87782. this.vertices[vId[j]].isBorder = true;
  87783. }
  87784. else {
  87785. this.vertices[vId[j]].isBorder = false;
  87786. }
  87787. }
  87788. }
  87789. };
  87790. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  87791. if (identifyBorders === void 0) { identifyBorders = false; }
  87792. var i;
  87793. if (!identifyBorders) {
  87794. var newTrianglesVector = [];
  87795. for (i = 0; i < this.triangles.length; ++i) {
  87796. if (!this.triangles[i].deleted) {
  87797. newTrianglesVector.push(this.triangles[i]);
  87798. }
  87799. }
  87800. this.triangles = newTrianglesVector;
  87801. }
  87802. for (i = 0; i < this.vertices.length; ++i) {
  87803. this.vertices[i].triangleCount = 0;
  87804. this.vertices[i].triangleStart = 0;
  87805. }
  87806. var t;
  87807. var j;
  87808. var v;
  87809. for (i = 0; i < this.triangles.length; ++i) {
  87810. t = this.triangles[i];
  87811. for (j = 0; j < 3; ++j) {
  87812. v = t.vertices[j];
  87813. v.triangleCount++;
  87814. }
  87815. }
  87816. var tStart = 0;
  87817. for (i = 0; i < this.vertices.length; ++i) {
  87818. this.vertices[i].triangleStart = tStart;
  87819. tStart += this.vertices[i].triangleCount;
  87820. this.vertices[i].triangleCount = 0;
  87821. }
  87822. var newReferences = new Array(this.triangles.length * 3);
  87823. for (i = 0; i < this.triangles.length; ++i) {
  87824. t = this.triangles[i];
  87825. for (j = 0; j < 3; ++j) {
  87826. v = t.vertices[j];
  87827. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  87828. v.triangleCount++;
  87829. }
  87830. }
  87831. this.references = newReferences;
  87832. if (identifyBorders) {
  87833. this.identifyBorder();
  87834. }
  87835. };
  87836. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  87837. var x = point.x;
  87838. var y = point.y;
  87839. var z = point.z;
  87840. 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
  87841. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  87842. };
  87843. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  87844. var q = vertex1.q.add(vertex2.q);
  87845. var border = vertex1.isBorder && vertex2.isBorder;
  87846. var error = 0;
  87847. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  87848. if (qDet !== 0 && !border) {
  87849. if (!pointResult) {
  87850. pointResult = BABYLON.Vector3.Zero();
  87851. }
  87852. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  87853. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  87854. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  87855. error = this.vertexError(q, pointResult);
  87856. }
  87857. else {
  87858. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  87859. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  87860. var error1 = this.vertexError(q, vertex1.position);
  87861. var error2 = this.vertexError(q, vertex2.position);
  87862. var error3 = this.vertexError(q, p3);
  87863. error = Math.min(error1, error2, error3);
  87864. if (error === error1) {
  87865. if (pointResult) {
  87866. pointResult.copyFrom(vertex1.position);
  87867. }
  87868. }
  87869. else if (error === error2) {
  87870. if (pointResult) {
  87871. pointResult.copyFrom(vertex2.position);
  87872. }
  87873. }
  87874. else {
  87875. if (pointResult) {
  87876. pointResult.copyFrom(p3);
  87877. }
  87878. }
  87879. }
  87880. return error;
  87881. };
  87882. return QuadraticErrorSimplification;
  87883. }());
  87884. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  87885. })(BABYLON || (BABYLON = {}));
  87886. //# sourceMappingURL=babylon.meshSimplification.js.map
  87887. "use strict";
  87888. var BABYLON;
  87889. (function (BABYLON) {
  87890. var MeshLODLevel = /** @class */ (function () {
  87891. function MeshLODLevel(distance, mesh) {
  87892. this.distance = distance;
  87893. this.mesh = mesh;
  87894. }
  87895. return MeshLODLevel;
  87896. }());
  87897. BABYLON.MeshLODLevel = MeshLODLevel;
  87898. })(BABYLON || (BABYLON = {}));
  87899. //# sourceMappingURL=babylon.meshLODLevel.js.map
  87900. "use strict";
  87901. var BABYLON;
  87902. (function (BABYLON) {
  87903. /**
  87904. * Defines the root class used to create scene optimization to use with SceneOptimizer
  87905. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87906. */
  87907. var SceneOptimization = /** @class */ (function () {
  87908. /**
  87909. * Creates the SceneOptimization object
  87910. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87911. * @param desc defines the description associated with the optimization
  87912. */
  87913. function SceneOptimization(
  87914. /**
  87915. * Defines the priority of this optimization (0 by default which means first in the list)
  87916. */
  87917. priority) {
  87918. if (priority === void 0) { priority = 0; }
  87919. this.priority = priority;
  87920. }
  87921. /**
  87922. * Gets a string describing the action executed by the current optimization
  87923. * @returns description string
  87924. */
  87925. SceneOptimization.prototype.getDescription = function () {
  87926. return "";
  87927. };
  87928. /**
  87929. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87930. * @param scene defines the current scene where to apply this optimization
  87931. * @param optimizer defines the current optimizer
  87932. * @returns true if everything that can be done was applied
  87933. */
  87934. SceneOptimization.prototype.apply = function (scene, optimizer) {
  87935. return true;
  87936. };
  87937. ;
  87938. return SceneOptimization;
  87939. }());
  87940. BABYLON.SceneOptimization = SceneOptimization;
  87941. /**
  87942. * Defines an optimization used to reduce the size of render target textures
  87943. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87944. */
  87945. var TextureOptimization = /** @class */ (function (_super) {
  87946. __extends(TextureOptimization, _super);
  87947. /**
  87948. * Creates the TextureOptimization object
  87949. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87950. * @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
  87951. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  87952. */
  87953. function TextureOptimization(
  87954. /**
  87955. * Defines the priority of this optimization (0 by default which means first in the list)
  87956. */
  87957. priority,
  87958. /**
  87959. * 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
  87960. */
  87961. maximumSize,
  87962. /**
  87963. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  87964. */
  87965. step) {
  87966. if (priority === void 0) { priority = 0; }
  87967. if (maximumSize === void 0) { maximumSize = 1024; }
  87968. if (step === void 0) { step = 0.5; }
  87969. var _this = _super.call(this, priority) || this;
  87970. _this.priority = priority;
  87971. _this.maximumSize = maximumSize;
  87972. _this.step = step;
  87973. return _this;
  87974. }
  87975. /**
  87976. * Gets a string describing the action executed by the current optimization
  87977. * @returns description string
  87978. */
  87979. TextureOptimization.prototype.getDescription = function () {
  87980. return "Reducing render target texture size to " + this.maximumSize;
  87981. };
  87982. /**
  87983. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87984. * @param scene defines the current scene where to apply this optimization
  87985. * @param optimizer defines the current optimizer
  87986. * @returns true if everything that can be done was applied
  87987. */
  87988. TextureOptimization.prototype.apply = function (scene, optimizer) {
  87989. var allDone = true;
  87990. for (var index = 0; index < scene.textures.length; index++) {
  87991. var texture = scene.textures[index];
  87992. if (!texture.canRescale || texture.getContext) {
  87993. continue;
  87994. }
  87995. var currentSize = texture.getSize();
  87996. var maxDimension = Math.max(currentSize.width, currentSize.height);
  87997. if (maxDimension > this.maximumSize) {
  87998. texture.scale(this.step);
  87999. allDone = false;
  88000. }
  88001. }
  88002. return allDone;
  88003. };
  88004. return TextureOptimization;
  88005. }(SceneOptimization));
  88006. BABYLON.TextureOptimization = TextureOptimization;
  88007. /**
  88008. * Defines an optimization used to increase or decrease the rendering resolution
  88009. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88010. */
  88011. var HardwareScalingOptimization = /** @class */ (function (_super) {
  88012. __extends(HardwareScalingOptimization, _super);
  88013. /**
  88014. * Creates the HardwareScalingOptimization object
  88015. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88016. * @param maximumScale defines the maximum scale to use (2 by default)
  88017. * @param step defines the step to use between two passes (0.5 by default)
  88018. */
  88019. function HardwareScalingOptimization(
  88020. /**
  88021. * Defines the priority of this optimization (0 by default which means first in the list)
  88022. */
  88023. priority,
  88024. /**
  88025. * Defines the maximum scale to use (2 by default)
  88026. */
  88027. maximumScale,
  88028. /**
  88029. * Defines the step to use between two passes (0.5 by default)
  88030. */
  88031. step) {
  88032. if (priority === void 0) { priority = 0; }
  88033. if (maximumScale === void 0) { maximumScale = 2; }
  88034. if (step === void 0) { step = 0.25; }
  88035. var _this = _super.call(this, priority) || this;
  88036. _this.priority = priority;
  88037. _this.maximumScale = maximumScale;
  88038. _this.step = step;
  88039. _this._currentScale = -1;
  88040. _this._directionOffset = 1;
  88041. return _this;
  88042. }
  88043. /**
  88044. * Gets a string describing the action executed by the current optimization
  88045. * @return description string
  88046. */
  88047. HardwareScalingOptimization.prototype.getDescription = function () {
  88048. return "Setting hardware scaling level to " + this._currentScale;
  88049. };
  88050. /**
  88051. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88052. * @param scene defines the current scene where to apply this optimization
  88053. * @param optimizer defines the current optimizer
  88054. * @returns true if everything that can be done was applied
  88055. */
  88056. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  88057. if (this._currentScale === -1) {
  88058. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  88059. if (this._currentScale > this.maximumScale) {
  88060. this._directionOffset = -1;
  88061. }
  88062. }
  88063. this._currentScale += this._directionOffset * this.step;
  88064. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  88065. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  88066. };
  88067. ;
  88068. return HardwareScalingOptimization;
  88069. }(SceneOptimization));
  88070. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  88071. /**
  88072. * Defines an optimization used to remove shadows
  88073. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88074. */
  88075. var ShadowsOptimization = /** @class */ (function (_super) {
  88076. __extends(ShadowsOptimization, _super);
  88077. function ShadowsOptimization() {
  88078. return _super !== null && _super.apply(this, arguments) || this;
  88079. }
  88080. /**
  88081. * Gets a string describing the action executed by the current optimization
  88082. * @return description string
  88083. */
  88084. ShadowsOptimization.prototype.getDescription = function () {
  88085. return "Turning shadows on/off";
  88086. };
  88087. /**
  88088. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88089. * @param scene defines the current scene where to apply this optimization
  88090. * @param optimizer defines the current optimizer
  88091. * @returns true if everything that can be done was applied
  88092. */
  88093. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  88094. scene.shadowsEnabled = optimizer.isInImprovementMode;
  88095. return true;
  88096. };
  88097. ;
  88098. return ShadowsOptimization;
  88099. }(SceneOptimization));
  88100. BABYLON.ShadowsOptimization = ShadowsOptimization;
  88101. /**
  88102. * Defines an optimization used to turn post-processes off
  88103. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88104. */
  88105. var PostProcessesOptimization = /** @class */ (function (_super) {
  88106. __extends(PostProcessesOptimization, _super);
  88107. function PostProcessesOptimization() {
  88108. return _super !== null && _super.apply(this, arguments) || this;
  88109. }
  88110. /**
  88111. * Gets a string describing the action executed by the current optimization
  88112. * @return description string
  88113. */
  88114. PostProcessesOptimization.prototype.getDescription = function () {
  88115. return "Turning post-processes on/off";
  88116. };
  88117. /**
  88118. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88119. * @param scene defines the current scene where to apply this optimization
  88120. * @param optimizer defines the current optimizer
  88121. * @returns true if everything that can be done was applied
  88122. */
  88123. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  88124. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  88125. return true;
  88126. };
  88127. ;
  88128. return PostProcessesOptimization;
  88129. }(SceneOptimization));
  88130. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  88131. /**
  88132. * Defines an optimization used to turn lens flares off
  88133. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88134. */
  88135. var LensFlaresOptimization = /** @class */ (function (_super) {
  88136. __extends(LensFlaresOptimization, _super);
  88137. function LensFlaresOptimization() {
  88138. return _super !== null && _super.apply(this, arguments) || this;
  88139. }
  88140. /**
  88141. * Gets a string describing the action executed by the current optimization
  88142. * @return description string
  88143. */
  88144. LensFlaresOptimization.prototype.getDescription = function () {
  88145. return "Turning lens flares on/off";
  88146. };
  88147. /**
  88148. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88149. * @param scene defines the current scene where to apply this optimization
  88150. * @param optimizer defines the current optimizer
  88151. * @returns true if everything that can be done was applied
  88152. */
  88153. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  88154. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  88155. return true;
  88156. };
  88157. ;
  88158. return LensFlaresOptimization;
  88159. }(SceneOptimization));
  88160. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  88161. /**
  88162. * Defines an optimization based on user defined callback.
  88163. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88164. */
  88165. var CustomOptimization = /** @class */ (function (_super) {
  88166. __extends(CustomOptimization, _super);
  88167. function CustomOptimization() {
  88168. return _super !== null && _super.apply(this, arguments) || this;
  88169. }
  88170. /**
  88171. * Gets a string describing the action executed by the current optimization
  88172. * @returns description string
  88173. */
  88174. CustomOptimization.prototype.getDescription = function () {
  88175. if (this.onGetDescription) {
  88176. return this.onGetDescription();
  88177. }
  88178. return "Running user defined callback";
  88179. };
  88180. /**
  88181. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88182. * @param scene defines the current scene where to apply this optimization
  88183. * @param optimizer defines the current optimizer
  88184. * @returns true if everything that can be done was applied
  88185. */
  88186. CustomOptimization.prototype.apply = function (scene, optimizer) {
  88187. if (this.onApply) {
  88188. return this.onApply(scene, optimizer);
  88189. }
  88190. return true;
  88191. };
  88192. ;
  88193. return CustomOptimization;
  88194. }(SceneOptimization));
  88195. BABYLON.CustomOptimization = CustomOptimization;
  88196. /**
  88197. * Defines an optimization used to turn particles off
  88198. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88199. */
  88200. var ParticlesOptimization = /** @class */ (function (_super) {
  88201. __extends(ParticlesOptimization, _super);
  88202. function ParticlesOptimization() {
  88203. return _super !== null && _super.apply(this, arguments) || this;
  88204. }
  88205. /**
  88206. * Gets a string describing the action executed by the current optimization
  88207. * @return description string
  88208. */
  88209. ParticlesOptimization.prototype.getDescription = function () {
  88210. return "Turning particles on/off";
  88211. };
  88212. /**
  88213. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88214. * @param scene defines the current scene where to apply this optimization
  88215. * @param optimizer defines the current optimizer
  88216. * @returns true if everything that can be done was applied
  88217. */
  88218. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  88219. scene.particlesEnabled = optimizer.isInImprovementMode;
  88220. return true;
  88221. };
  88222. ;
  88223. return ParticlesOptimization;
  88224. }(SceneOptimization));
  88225. BABYLON.ParticlesOptimization = ParticlesOptimization;
  88226. /**
  88227. * Defines an optimization used to turn render targets off
  88228. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88229. */
  88230. var RenderTargetsOptimization = /** @class */ (function (_super) {
  88231. __extends(RenderTargetsOptimization, _super);
  88232. function RenderTargetsOptimization() {
  88233. return _super !== null && _super.apply(this, arguments) || this;
  88234. }
  88235. /**
  88236. * Gets a string describing the action executed by the current optimization
  88237. * @return description string
  88238. */
  88239. RenderTargetsOptimization.prototype.getDescription = function () {
  88240. return "Turning render targets off";
  88241. };
  88242. /**
  88243. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88244. * @param scene defines the current scene where to apply this optimization
  88245. * @param optimizer defines the current optimizer
  88246. * @returns true if everything that can be done was applied
  88247. */
  88248. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  88249. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  88250. return true;
  88251. };
  88252. ;
  88253. return RenderTargetsOptimization;
  88254. }(SceneOptimization));
  88255. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  88256. /**
  88257. * Defines an optimization used to merge meshes with compatible materials
  88258. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88259. */
  88260. var MergeMeshesOptimization = /** @class */ (function (_super) {
  88261. __extends(MergeMeshesOptimization, _super);
  88262. function MergeMeshesOptimization() {
  88263. var _this = _super !== null && _super.apply(this, arguments) || this;
  88264. _this._canBeMerged = function (abstractMesh) {
  88265. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  88266. return false;
  88267. }
  88268. var mesh = abstractMesh;
  88269. if (!mesh.isVisible || !mesh.isEnabled()) {
  88270. return false;
  88271. }
  88272. if (mesh.instances.length > 0) {
  88273. return false;
  88274. }
  88275. if (mesh.skeleton || mesh.hasLODLevels) {
  88276. return false;
  88277. }
  88278. if (mesh.parent) {
  88279. return false;
  88280. }
  88281. return true;
  88282. };
  88283. return _this;
  88284. }
  88285. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  88286. /**
  88287. * Gets or sets a boolean which defines if optimization octree has to be updated
  88288. */
  88289. get: function () {
  88290. return MergeMeshesOptimization._UpdateSelectionTree;
  88291. },
  88292. /**
  88293. * Gets or sets a boolean which defines if optimization octree has to be updated
  88294. */
  88295. set: function (value) {
  88296. MergeMeshesOptimization._UpdateSelectionTree = value;
  88297. },
  88298. enumerable: true,
  88299. configurable: true
  88300. });
  88301. /**
  88302. * Gets a string describing the action executed by the current optimization
  88303. * @return description string
  88304. */
  88305. MergeMeshesOptimization.prototype.getDescription = function () {
  88306. return "Merging similar meshes together";
  88307. };
  88308. /**
  88309. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88310. * @param scene defines the current scene where to apply this optimization
  88311. * @param optimizer defines the current optimizer
  88312. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  88313. * @returns true if everything that can be done was applied
  88314. */
  88315. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  88316. var globalPool = scene.meshes.slice(0);
  88317. var globalLength = globalPool.length;
  88318. for (var index = 0; index < globalLength; index++) {
  88319. var currentPool = new Array();
  88320. var current = globalPool[index];
  88321. // Checks
  88322. if (!this._canBeMerged(current)) {
  88323. continue;
  88324. }
  88325. currentPool.push(current);
  88326. // Find compatible meshes
  88327. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  88328. var otherMesh = globalPool[subIndex];
  88329. if (!this._canBeMerged(otherMesh)) {
  88330. continue;
  88331. }
  88332. if (otherMesh.material !== current.material) {
  88333. continue;
  88334. }
  88335. if (otherMesh.checkCollisions !== current.checkCollisions) {
  88336. continue;
  88337. }
  88338. currentPool.push(otherMesh);
  88339. globalLength--;
  88340. globalPool.splice(subIndex, 1);
  88341. subIndex--;
  88342. }
  88343. if (currentPool.length < 2) {
  88344. continue;
  88345. }
  88346. // Merge meshes
  88347. BABYLON.Mesh.MergeMeshes(currentPool);
  88348. }
  88349. if (updateSelectionTree != undefined) {
  88350. if (updateSelectionTree) {
  88351. scene.createOrUpdateSelectionOctree();
  88352. }
  88353. }
  88354. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  88355. scene.createOrUpdateSelectionOctree();
  88356. }
  88357. return true;
  88358. };
  88359. ;
  88360. MergeMeshesOptimization._UpdateSelectionTree = false;
  88361. return MergeMeshesOptimization;
  88362. }(SceneOptimization));
  88363. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  88364. /**
  88365. * Defines a list of options used by SceneOptimizer
  88366. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88367. */
  88368. var SceneOptimizerOptions = /** @class */ (function () {
  88369. /**
  88370. * Creates a new list of options used by SceneOptimizer
  88371. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  88372. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  88373. */
  88374. function SceneOptimizerOptions(
  88375. /**
  88376. * Defines the target frame rate to reach (60 by default)
  88377. */
  88378. targetFrameRate,
  88379. /**
  88380. * Defines the interval between two checkes (2000ms by default)
  88381. */
  88382. trackerDuration) {
  88383. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  88384. if (trackerDuration === void 0) { trackerDuration = 2000; }
  88385. this.targetFrameRate = targetFrameRate;
  88386. this.trackerDuration = trackerDuration;
  88387. /**
  88388. * Gets the list of optimizations to apply
  88389. */
  88390. this.optimizations = new Array();
  88391. }
  88392. /**
  88393. * Add a new optimization
  88394. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  88395. * @returns the current SceneOptimizerOptions
  88396. */
  88397. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  88398. this.optimizations.push(optimization);
  88399. return this;
  88400. };
  88401. /**
  88402. * Add a new custom optimization
  88403. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  88404. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  88405. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88406. * @returns the current SceneOptimizerOptions
  88407. */
  88408. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  88409. if (priority === void 0) { priority = 0; }
  88410. var optimization = new CustomOptimization(priority);
  88411. optimization.onApply = onApply;
  88412. optimization.onGetDescription = onGetDescription;
  88413. this.optimizations.push(optimization);
  88414. return this;
  88415. };
  88416. /**
  88417. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  88418. * @param targetFrameRate defines the target frame rate (60 by default)
  88419. * @returns a SceneOptimizerOptions object
  88420. */
  88421. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  88422. var result = new SceneOptimizerOptions(targetFrameRate);
  88423. var priority = 0;
  88424. result.addOptimization(new MergeMeshesOptimization(priority));
  88425. result.addOptimization(new ShadowsOptimization(priority));
  88426. result.addOptimization(new LensFlaresOptimization(priority));
  88427. // Next priority
  88428. priority++;
  88429. result.addOptimization(new PostProcessesOptimization(priority));
  88430. result.addOptimization(new ParticlesOptimization(priority));
  88431. // Next priority
  88432. priority++;
  88433. result.addOptimization(new TextureOptimization(priority, 1024));
  88434. return result;
  88435. };
  88436. /**
  88437. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  88438. * @param targetFrameRate defines the target frame rate (60 by default)
  88439. * @returns a SceneOptimizerOptions object
  88440. */
  88441. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  88442. var result = new SceneOptimizerOptions(targetFrameRate);
  88443. var priority = 0;
  88444. result.addOptimization(new MergeMeshesOptimization(priority));
  88445. result.addOptimization(new ShadowsOptimization(priority));
  88446. result.addOptimization(new LensFlaresOptimization(priority));
  88447. // Next priority
  88448. priority++;
  88449. result.addOptimization(new PostProcessesOptimization(priority));
  88450. result.addOptimization(new ParticlesOptimization(priority));
  88451. // Next priority
  88452. priority++;
  88453. result.addOptimization(new TextureOptimization(priority, 512));
  88454. // Next priority
  88455. priority++;
  88456. result.addOptimization(new RenderTargetsOptimization(priority));
  88457. // Next priority
  88458. priority++;
  88459. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  88460. return result;
  88461. };
  88462. /**
  88463. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  88464. * @param targetFrameRate defines the target frame rate (60 by default)
  88465. * @returns a SceneOptimizerOptions object
  88466. */
  88467. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  88468. var result = new SceneOptimizerOptions(targetFrameRate);
  88469. var priority = 0;
  88470. result.addOptimization(new MergeMeshesOptimization(priority));
  88471. result.addOptimization(new ShadowsOptimization(priority));
  88472. result.addOptimization(new LensFlaresOptimization(priority));
  88473. // Next priority
  88474. priority++;
  88475. result.addOptimization(new PostProcessesOptimization(priority));
  88476. result.addOptimization(new ParticlesOptimization(priority));
  88477. // Next priority
  88478. priority++;
  88479. result.addOptimization(new TextureOptimization(priority, 256));
  88480. // Next priority
  88481. priority++;
  88482. result.addOptimization(new RenderTargetsOptimization(priority));
  88483. // Next priority
  88484. priority++;
  88485. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  88486. return result;
  88487. };
  88488. return SceneOptimizerOptions;
  88489. }());
  88490. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  88491. /**
  88492. * Class used to run optimizations in order to reach a target frame rate
  88493. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88494. */
  88495. var SceneOptimizer = /** @class */ (function () {
  88496. /**
  88497. * Creates a new SceneOptimizer
  88498. * @param scene defines the scene to work on
  88499. * @param options defines the options to use with the SceneOptimizer
  88500. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  88501. * @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)
  88502. */
  88503. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  88504. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  88505. if (improvementMode === void 0) { improvementMode = false; }
  88506. var _this = this;
  88507. this._isRunning = false;
  88508. this._currentPriorityLevel = 0;
  88509. this._targetFrameRate = 60;
  88510. this._trackerDuration = 2000;
  88511. this._currentFrameRate = 0;
  88512. this._improvementMode = false;
  88513. /**
  88514. * Defines an observable called when the optimizer reaches the target frame rate
  88515. */
  88516. this.onSuccessObservable = new BABYLON.Observable();
  88517. /**
  88518. * Defines an observable called when the optimizer enables an optimization
  88519. */
  88520. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  88521. /**
  88522. * Defines an observable called when the optimizer is not able to reach the target frame rate
  88523. */
  88524. this.onFailureObservable = new BABYLON.Observable();
  88525. if (!options) {
  88526. this._options = new SceneOptimizerOptions();
  88527. }
  88528. else {
  88529. this._options = options;
  88530. }
  88531. if (this._options.targetFrameRate) {
  88532. this._targetFrameRate = this._options.targetFrameRate;
  88533. }
  88534. if (this._options.trackerDuration) {
  88535. this._trackerDuration = this._options.trackerDuration;
  88536. }
  88537. if (autoGeneratePriorities) {
  88538. var priority = 0;
  88539. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  88540. var optim = _a[_i];
  88541. optim.priority = priority++;
  88542. }
  88543. }
  88544. this._improvementMode = improvementMode;
  88545. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88546. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  88547. _this._sceneDisposeObserver = null;
  88548. _this.dispose();
  88549. });
  88550. }
  88551. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  88552. /**
  88553. * Gets a boolean indicating if the optimizer is in improvement mode
  88554. */
  88555. get: function () {
  88556. return this._improvementMode;
  88557. },
  88558. enumerable: true,
  88559. configurable: true
  88560. });
  88561. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  88562. /**
  88563. * Gets the current priority level (0 at start)
  88564. */
  88565. get: function () {
  88566. return this._currentPriorityLevel;
  88567. },
  88568. enumerable: true,
  88569. configurable: true
  88570. });
  88571. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  88572. /**
  88573. * Gets the current frame rate checked by the SceneOptimizer
  88574. */
  88575. get: function () {
  88576. return this._currentFrameRate;
  88577. },
  88578. enumerable: true,
  88579. configurable: true
  88580. });
  88581. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  88582. /**
  88583. * Gets or sets the current target frame rate (60 by default)
  88584. */
  88585. get: function () {
  88586. return this._targetFrameRate;
  88587. },
  88588. /**
  88589. * Gets or sets the current target frame rate (60 by default)
  88590. */
  88591. set: function (value) {
  88592. this._targetFrameRate = value;
  88593. },
  88594. enumerable: true,
  88595. configurable: true
  88596. });
  88597. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  88598. /**
  88599. * Gets or sets the current interval between two checks (every 2000ms by default)
  88600. */
  88601. get: function () {
  88602. return this._trackerDuration;
  88603. },
  88604. /**
  88605. * Gets or sets the current interval between two checks (every 2000ms by default)
  88606. */
  88607. set: function (value) {
  88608. this._trackerDuration = value;
  88609. },
  88610. enumerable: true,
  88611. configurable: true
  88612. });
  88613. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  88614. /**
  88615. * Gets the list of active optimizations
  88616. */
  88617. get: function () {
  88618. return this._options.optimizations;
  88619. },
  88620. enumerable: true,
  88621. configurable: true
  88622. });
  88623. /**
  88624. * Stops the current optimizer
  88625. */
  88626. SceneOptimizer.prototype.stop = function () {
  88627. this._isRunning = false;
  88628. };
  88629. /**
  88630. * Reset the optimizer to initial step (current priority level = 0)
  88631. */
  88632. SceneOptimizer.prototype.reset = function () {
  88633. this._currentPriorityLevel = 0;
  88634. };
  88635. /**
  88636. * Start the optimizer. By default it will try to reach a specific framerate
  88637. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  88638. */
  88639. SceneOptimizer.prototype.start = function () {
  88640. var _this = this;
  88641. if (this._isRunning) {
  88642. return;
  88643. }
  88644. this._isRunning = true;
  88645. // Let's wait for the scene to be ready before running our check
  88646. this._scene.executeWhenReady(function () {
  88647. setTimeout(function () {
  88648. _this._checkCurrentState();
  88649. }, _this._trackerDuration);
  88650. });
  88651. };
  88652. SceneOptimizer.prototype._checkCurrentState = function () {
  88653. var _this = this;
  88654. if (!this._isRunning) {
  88655. return;
  88656. }
  88657. var scene = this._scene;
  88658. var options = this._options;
  88659. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  88660. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  88661. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  88662. this._isRunning = false;
  88663. this.onSuccessObservable.notifyObservers(this);
  88664. return;
  88665. }
  88666. // Apply current level of optimizations
  88667. var allDone = true;
  88668. var noOptimizationApplied = true;
  88669. for (var index = 0; index < options.optimizations.length; index++) {
  88670. var optimization = options.optimizations[index];
  88671. if (optimization.priority === this._currentPriorityLevel) {
  88672. noOptimizationApplied = false;
  88673. allDone = allDone && optimization.apply(scene, this);
  88674. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  88675. }
  88676. }
  88677. // If no optimization was applied, this is a failure :(
  88678. if (noOptimizationApplied) {
  88679. this._isRunning = false;
  88680. this.onFailureObservable.notifyObservers(this);
  88681. return;
  88682. }
  88683. // If all optimizations were done, move to next level
  88684. if (allDone) {
  88685. this._currentPriorityLevel++;
  88686. }
  88687. // Let's the system running for a specific amount of time before checking FPS
  88688. scene.executeWhenReady(function () {
  88689. setTimeout(function () {
  88690. _this._checkCurrentState();
  88691. }, _this._trackerDuration);
  88692. });
  88693. };
  88694. /**
  88695. * Release all resources
  88696. */
  88697. SceneOptimizer.prototype.dispose = function () {
  88698. this.stop();
  88699. this.onSuccessObservable.clear();
  88700. this.onFailureObservable.clear();
  88701. this.onNewOptimizationAppliedObservable.clear();
  88702. if (this._sceneDisposeObserver) {
  88703. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88704. }
  88705. };
  88706. /**
  88707. * Helper function to create a SceneOptimizer with one single line of code
  88708. * @param scene defines the scene to work on
  88709. * @param options defines the options to use with the SceneOptimizer
  88710. * @param onSuccess defines a callback to call on success
  88711. * @param onFailure defines a callback to call on failure
  88712. * @returns the new SceneOptimizer object
  88713. */
  88714. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  88715. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  88716. if (onSuccess) {
  88717. optimizer.onSuccessObservable.add(function () {
  88718. onSuccess();
  88719. });
  88720. }
  88721. if (onFailure) {
  88722. optimizer.onFailureObservable.add(function () {
  88723. onFailure();
  88724. });
  88725. }
  88726. optimizer.start();
  88727. return optimizer;
  88728. };
  88729. return SceneOptimizer;
  88730. }());
  88731. BABYLON.SceneOptimizer = SceneOptimizer;
  88732. })(BABYLON || (BABYLON = {}));
  88733. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  88734. "use strict";
  88735. var BABYLON;
  88736. (function (BABYLON) {
  88737. var OutlineRenderer = /** @class */ (function () {
  88738. function OutlineRenderer(scene) {
  88739. this.zOffset = 1;
  88740. this._scene = scene;
  88741. }
  88742. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  88743. var _this = this;
  88744. if (useOverlay === void 0) { useOverlay = false; }
  88745. var scene = this._scene;
  88746. var engine = this._scene.getEngine();
  88747. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  88748. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  88749. return;
  88750. }
  88751. var mesh = subMesh.getRenderingMesh();
  88752. var material = subMesh.getMaterial();
  88753. if (!material || !scene.activeCamera) {
  88754. return;
  88755. }
  88756. engine.enableEffect(this._effect);
  88757. // Logarithmic depth
  88758. if (material.useLogarithmicDepth) {
  88759. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  88760. }
  88761. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  88762. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  88763. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  88764. // Bones
  88765. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  88766. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  88767. }
  88768. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  88769. // Alpha test
  88770. if (material && material.needAlphaTesting()) {
  88771. var alphaTexture = material.getAlphaTestTexture();
  88772. if (alphaTexture) {
  88773. this._effect.setTexture("diffuseSampler", alphaTexture);
  88774. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  88775. }
  88776. }
  88777. engine.setZOffset(-this.zOffset);
  88778. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  88779. engine.setZOffset(0);
  88780. };
  88781. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  88782. var defines = [];
  88783. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  88784. var mesh = subMesh.getMesh();
  88785. var material = subMesh.getMaterial();
  88786. if (material) {
  88787. // Alpha test
  88788. if (material.needAlphaTesting()) {
  88789. defines.push("#define ALPHATEST");
  88790. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88791. attribs.push(BABYLON.VertexBuffer.UVKind);
  88792. defines.push("#define UV1");
  88793. }
  88794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  88795. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88796. defines.push("#define UV2");
  88797. }
  88798. }
  88799. //Logarithmic depth
  88800. if (material.useLogarithmicDepth) {
  88801. defines.push("#define LOGARITHMICDEPTH");
  88802. }
  88803. }
  88804. // Bones
  88805. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  88806. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  88807. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  88808. if (mesh.numBoneInfluencers > 4) {
  88809. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  88810. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  88811. }
  88812. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  88813. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  88814. }
  88815. else {
  88816. defines.push("#define NUM_BONE_INFLUENCERS 0");
  88817. }
  88818. // Instances
  88819. if (useInstances) {
  88820. defines.push("#define INSTANCES");
  88821. attribs.push("world0");
  88822. attribs.push("world1");
  88823. attribs.push("world2");
  88824. attribs.push("world3");
  88825. }
  88826. // Get correct effect
  88827. var join = defines.join("\n");
  88828. if (this._cachedDefines !== join) {
  88829. this._cachedDefines = join;
  88830. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  88831. }
  88832. return this._effect.isReady();
  88833. };
  88834. return OutlineRenderer;
  88835. }());
  88836. BABYLON.OutlineRenderer = OutlineRenderer;
  88837. })(BABYLON || (BABYLON = {}));
  88838. //# sourceMappingURL=babylon.outlineRenderer.js.map
  88839. "use strict";
  88840. var BABYLON;
  88841. (function (BABYLON) {
  88842. var FaceAdjacencies = /** @class */ (function () {
  88843. function FaceAdjacencies() {
  88844. this.edges = new Array();
  88845. this.edgesConnectedCount = 0;
  88846. }
  88847. return FaceAdjacencies;
  88848. }());
  88849. var EdgesRenderer = /** @class */ (function () {
  88850. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  88851. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  88852. if (epsilon === void 0) { epsilon = 0.95; }
  88853. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  88854. this.edgesWidthScalerForOrthographic = 1000.0;
  88855. this.edgesWidthScalerForPerspective = 50.0;
  88856. this._linesPositions = new Array();
  88857. this._linesNormals = new Array();
  88858. this._linesIndices = new Array();
  88859. this._buffers = {};
  88860. this._checkVerticesInsteadOfIndices = false;
  88861. this._source = source;
  88862. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  88863. this._epsilon = epsilon;
  88864. this._prepareRessources();
  88865. this._generateEdgesLines();
  88866. }
  88867. EdgesRenderer.prototype._prepareRessources = function () {
  88868. if (this._lineShader) {
  88869. return;
  88870. }
  88871. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  88872. attributes: ["position", "normal"],
  88873. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  88874. });
  88875. this._lineShader.disableDepthWrite = true;
  88876. this._lineShader.backFaceCulling = false;
  88877. };
  88878. EdgesRenderer.prototype._rebuild = function () {
  88879. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  88880. if (buffer) {
  88881. buffer._rebuild();
  88882. }
  88883. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  88884. if (buffer) {
  88885. buffer._rebuild();
  88886. }
  88887. var scene = this._source.getScene();
  88888. var engine = scene.getEngine();
  88889. this._ib = engine.createIndexBuffer(this._linesIndices);
  88890. };
  88891. EdgesRenderer.prototype.dispose = function () {
  88892. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  88893. if (buffer) {
  88894. buffer.dispose();
  88895. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  88896. }
  88897. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  88898. if (buffer) {
  88899. buffer.dispose();
  88900. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  88901. }
  88902. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  88903. this._lineShader.dispose();
  88904. };
  88905. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  88906. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  88907. return 0;
  88908. }
  88909. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  88910. return 1;
  88911. }
  88912. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  88913. return 2;
  88914. }
  88915. return -1;
  88916. };
  88917. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  88918. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  88919. return 0;
  88920. }
  88921. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  88922. return 1;
  88923. }
  88924. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  88925. return 2;
  88926. }
  88927. return -1;
  88928. };
  88929. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  88930. var needToCreateLine;
  88931. if (edge === undefined) {
  88932. needToCreateLine = true;
  88933. }
  88934. else {
  88935. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  88936. needToCreateLine = dotProduct < this._epsilon;
  88937. }
  88938. if (needToCreateLine) {
  88939. var offset = this._linesPositions.length / 3;
  88940. var normal = p0.subtract(p1);
  88941. normal.normalize();
  88942. // Positions
  88943. this._linesPositions.push(p0.x);
  88944. this._linesPositions.push(p0.y);
  88945. this._linesPositions.push(p0.z);
  88946. this._linesPositions.push(p0.x);
  88947. this._linesPositions.push(p0.y);
  88948. this._linesPositions.push(p0.z);
  88949. this._linesPositions.push(p1.x);
  88950. this._linesPositions.push(p1.y);
  88951. this._linesPositions.push(p1.z);
  88952. this._linesPositions.push(p1.x);
  88953. this._linesPositions.push(p1.y);
  88954. this._linesPositions.push(p1.z);
  88955. // Normals
  88956. this._linesNormals.push(p1.x);
  88957. this._linesNormals.push(p1.y);
  88958. this._linesNormals.push(p1.z);
  88959. this._linesNormals.push(-1);
  88960. this._linesNormals.push(p1.x);
  88961. this._linesNormals.push(p1.y);
  88962. this._linesNormals.push(p1.z);
  88963. this._linesNormals.push(1);
  88964. this._linesNormals.push(p0.x);
  88965. this._linesNormals.push(p0.y);
  88966. this._linesNormals.push(p0.z);
  88967. this._linesNormals.push(-1);
  88968. this._linesNormals.push(p0.x);
  88969. this._linesNormals.push(p0.y);
  88970. this._linesNormals.push(p0.z);
  88971. this._linesNormals.push(1);
  88972. // Indices
  88973. this._linesIndices.push(offset);
  88974. this._linesIndices.push(offset + 1);
  88975. this._linesIndices.push(offset + 2);
  88976. this._linesIndices.push(offset);
  88977. this._linesIndices.push(offset + 2);
  88978. this._linesIndices.push(offset + 3);
  88979. }
  88980. };
  88981. EdgesRenderer.prototype._generateEdgesLines = function () {
  88982. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88983. var indices = this._source.getIndices();
  88984. if (!indices || !positions) {
  88985. return;
  88986. }
  88987. // First let's find adjacencies
  88988. var adjacencies = new Array();
  88989. var faceNormals = new Array();
  88990. var index;
  88991. var faceAdjacencies;
  88992. // Prepare faces
  88993. for (index = 0; index < indices.length; index += 3) {
  88994. faceAdjacencies = new FaceAdjacencies();
  88995. var p0Index = indices[index];
  88996. var p1Index = indices[index + 1];
  88997. var p2Index = indices[index + 2];
  88998. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  88999. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  89000. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  89001. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  89002. faceNormal.normalize();
  89003. faceNormals.push(faceNormal);
  89004. adjacencies.push(faceAdjacencies);
  89005. }
  89006. // Scan
  89007. for (index = 0; index < adjacencies.length; index++) {
  89008. faceAdjacencies = adjacencies[index];
  89009. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  89010. var otherFaceAdjacencies = adjacencies[otherIndex];
  89011. if (faceAdjacencies.edgesConnectedCount === 3) {
  89012. break;
  89013. }
  89014. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  89015. continue;
  89016. }
  89017. var otherP0 = indices[otherIndex * 3];
  89018. var otherP1 = indices[otherIndex * 3 + 1];
  89019. var otherP2 = indices[otherIndex * 3 + 2];
  89020. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  89021. var otherEdgeIndex = 0;
  89022. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  89023. continue;
  89024. }
  89025. switch (edgeIndex) {
  89026. case 0:
  89027. if (this._checkVerticesInsteadOfIndices) {
  89028. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89029. }
  89030. else {
  89031. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  89032. }
  89033. break;
  89034. case 1:
  89035. if (this._checkVerticesInsteadOfIndices) {
  89036. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89037. }
  89038. else {
  89039. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  89040. }
  89041. break;
  89042. case 2:
  89043. if (this._checkVerticesInsteadOfIndices) {
  89044. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89045. }
  89046. else {
  89047. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  89048. }
  89049. break;
  89050. }
  89051. if (otherEdgeIndex === -1) {
  89052. continue;
  89053. }
  89054. faceAdjacencies.edges[edgeIndex] = otherIndex;
  89055. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  89056. faceAdjacencies.edgesConnectedCount++;
  89057. otherFaceAdjacencies.edgesConnectedCount++;
  89058. if (faceAdjacencies.edgesConnectedCount === 3) {
  89059. break;
  89060. }
  89061. }
  89062. }
  89063. }
  89064. // Create lines
  89065. for (index = 0; index < adjacencies.length; index++) {
  89066. // 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
  89067. var current = adjacencies[index];
  89068. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  89069. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  89070. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  89071. }
  89072. // Merge into a single mesh
  89073. var engine = this._source.getScene().getEngine();
  89074. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  89075. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  89076. this._ib = engine.createIndexBuffer(this._linesIndices);
  89077. this._indicesCount = this._linesIndices.length;
  89078. };
  89079. EdgesRenderer.prototype.render = function () {
  89080. var scene = this._source.getScene();
  89081. if (!this._lineShader.isReady() || !scene.activeCamera) {
  89082. return;
  89083. }
  89084. var engine = scene.getEngine();
  89085. this._lineShader._preBind();
  89086. // VBOs
  89087. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  89088. scene.resetCachedMaterial();
  89089. this._lineShader.setColor4("color", this._source.edgesColor);
  89090. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  89091. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  89092. }
  89093. else {
  89094. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  89095. }
  89096. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  89097. this._lineShader.bind(this._source.getWorldMatrix());
  89098. // Draw order
  89099. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  89100. this._lineShader.unbind();
  89101. engine.setDepthWrite(true);
  89102. };
  89103. return EdgesRenderer;
  89104. }());
  89105. BABYLON.EdgesRenderer = EdgesRenderer;
  89106. })(BABYLON || (BABYLON = {}));
  89107. //# sourceMappingURL=babylon.edgesRenderer.js.map
  89108. "use strict";
  89109. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89110. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89111. s = arguments[i];
  89112. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89113. t[p] = s[p];
  89114. }
  89115. return t;
  89116. };
  89117. var BABYLON;
  89118. (function (BABYLON) {
  89119. /**
  89120. * The effect layer Helps adding post process effect blended with the main pass.
  89121. *
  89122. * This can be for instance use to generate glow or higlight effects on the scene.
  89123. *
  89124. * The effect layer class can not be used directly and is intented to inherited from to be
  89125. * customized per effects.
  89126. */
  89127. var EffectLayer = /** @class */ (function () {
  89128. /**
  89129. * Instantiates a new effect Layer and references it in the scene.
  89130. * @param name The name of the layer
  89131. * @param scene The scene to use the layer in
  89132. */
  89133. function EffectLayer(
  89134. /** The Friendly of the effect in the scene */
  89135. name, scene) {
  89136. this._vertexBuffers = {};
  89137. this._maxSize = 0;
  89138. this._mainTextureDesiredSize = { width: 0, height: 0 };
  89139. this._shouldRender = true;
  89140. this._postProcesses = [];
  89141. this._textures = [];
  89142. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  89143. /**
  89144. * The clear color of the texture used to generate the glow map.
  89145. */
  89146. this.neutralColor = new BABYLON.Color4();
  89147. /**
  89148. * Specifies wether the highlight layer is enabled or not.
  89149. */
  89150. this.isEnabled = true;
  89151. /**
  89152. * An event triggered when the effect layer has been disposed.
  89153. */
  89154. this.onDisposeObservable = new BABYLON.Observable();
  89155. /**
  89156. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  89157. */
  89158. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  89159. /**
  89160. * An event triggered when the generated texture is being merged in the scene.
  89161. */
  89162. this.onBeforeComposeObservable = new BABYLON.Observable();
  89163. /**
  89164. * An event triggered when the generated texture has been merged in the scene.
  89165. */
  89166. this.onAfterComposeObservable = new BABYLON.Observable();
  89167. /**
  89168. * An event triggered when the efffect layer changes its size.
  89169. */
  89170. this.onSizeChangedObservable = new BABYLON.Observable();
  89171. this.name = name;
  89172. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89173. this._engine = scene.getEngine();
  89174. this._maxSize = this._engine.getCaps().maxTextureSize;
  89175. this._scene.effectLayers.push(this);
  89176. // Generate Buffers
  89177. this._generateIndexBuffer();
  89178. this._genrateVertexBuffer();
  89179. }
  89180. Object.defineProperty(EffectLayer.prototype, "camera", {
  89181. /**
  89182. * Gets the camera attached to the layer.
  89183. */
  89184. get: function () {
  89185. return this._effectLayerOptions.camera;
  89186. },
  89187. enumerable: true,
  89188. configurable: true
  89189. });
  89190. /**
  89191. * Initializes the effect layer with the required options.
  89192. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  89193. */
  89194. EffectLayer.prototype._init = function (options) {
  89195. // Adapt options
  89196. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  89197. this._setMainTextureSize();
  89198. this._createMainTexture();
  89199. this._createTextureAndPostProcesses();
  89200. this._mergeEffect = this._createMergeEffect();
  89201. };
  89202. /**
  89203. * Generates the index buffer of the full screen quad blending to the main canvas.
  89204. */
  89205. EffectLayer.prototype._generateIndexBuffer = function () {
  89206. // Indices
  89207. var indices = [];
  89208. indices.push(0);
  89209. indices.push(1);
  89210. indices.push(2);
  89211. indices.push(0);
  89212. indices.push(2);
  89213. indices.push(3);
  89214. this._indexBuffer = this._engine.createIndexBuffer(indices);
  89215. };
  89216. /**
  89217. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  89218. */
  89219. EffectLayer.prototype._genrateVertexBuffer = function () {
  89220. // VBO
  89221. var vertices = [];
  89222. vertices.push(1, 1);
  89223. vertices.push(-1, 1);
  89224. vertices.push(-1, -1);
  89225. vertices.push(1, -1);
  89226. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89227. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  89228. };
  89229. /**
  89230. * Sets the main texture desired size which is the closest power of two
  89231. * of the engine canvas size.
  89232. */
  89233. EffectLayer.prototype._setMainTextureSize = function () {
  89234. if (this._effectLayerOptions.mainTextureFixedSize) {
  89235. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  89236. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  89237. }
  89238. else {
  89239. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  89240. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  89241. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  89242. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  89243. }
  89244. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  89245. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  89246. };
  89247. /**
  89248. * Creates the main texture for the effect layer.
  89249. */
  89250. EffectLayer.prototype._createMainTexture = function () {
  89251. var _this = this;
  89252. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  89253. width: this._mainTextureDesiredSize.width,
  89254. height: this._mainTextureDesiredSize.height
  89255. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89256. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  89257. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89258. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89259. this._mainTexture.anisotropicFilteringLevel = 1;
  89260. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89261. this._mainTexture.renderParticles = false;
  89262. this._mainTexture.renderList = null;
  89263. this._mainTexture.ignoreCameraViewport = true;
  89264. // Custom render function
  89265. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89266. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  89267. var index;
  89268. var engine = _this._scene.getEngine();
  89269. if (depthOnlySubMeshes.length) {
  89270. engine.setColorWrite(false);
  89271. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89272. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  89273. }
  89274. engine.setColorWrite(true);
  89275. }
  89276. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89277. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  89278. }
  89279. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89280. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  89281. }
  89282. for (index = 0; index < transparentSubMeshes.length; index++) {
  89283. _this._renderSubMesh(transparentSubMeshes.data[index]);
  89284. }
  89285. };
  89286. this._mainTexture.onClearObservable.add(function (engine) {
  89287. engine.clear(_this.neutralColor, true, true, true);
  89288. });
  89289. };
  89290. /**
  89291. * Checks for the readiness of the element composing the layer.
  89292. * @param subMesh the mesh to check for
  89293. * @param useInstances specify wether or not to use instances to render the mesh
  89294. * @param emissiveTexture the associated emissive texture used to generate the glow
  89295. * @return true if ready otherwise, false
  89296. */
  89297. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  89298. var material = subMesh.getMaterial();
  89299. if (!material) {
  89300. return false;
  89301. }
  89302. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  89303. return false;
  89304. }
  89305. var defines = [];
  89306. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89307. var mesh = subMesh.getMesh();
  89308. var uv1 = false;
  89309. var uv2 = false;
  89310. // Alpha test
  89311. if (material && material.needAlphaTesting()) {
  89312. var alphaTexture = material.getAlphaTestTexture();
  89313. if (alphaTexture) {
  89314. defines.push("#define ALPHATEST");
  89315. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  89316. alphaTexture.coordinatesIndex === 1) {
  89317. defines.push("#define DIFFUSEUV2");
  89318. uv2 = true;
  89319. }
  89320. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89321. defines.push("#define DIFFUSEUV1");
  89322. uv1 = true;
  89323. }
  89324. }
  89325. }
  89326. // Emissive
  89327. if (emissiveTexture) {
  89328. defines.push("#define EMISSIVE");
  89329. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  89330. emissiveTexture.coordinatesIndex === 1) {
  89331. defines.push("#define EMISSIVEUV2");
  89332. uv2 = true;
  89333. }
  89334. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89335. defines.push("#define EMISSIVEUV1");
  89336. uv1 = true;
  89337. }
  89338. }
  89339. if (uv1) {
  89340. attribs.push(BABYLON.VertexBuffer.UVKind);
  89341. defines.push("#define UV1");
  89342. }
  89343. if (uv2) {
  89344. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89345. defines.push("#define UV2");
  89346. }
  89347. // Bones
  89348. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89349. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89350. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89351. if (mesh.numBoneInfluencers > 4) {
  89352. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  89353. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  89354. }
  89355. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89356. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  89357. }
  89358. else {
  89359. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89360. }
  89361. // Morph targets
  89362. var manager = mesh.morphTargetManager;
  89363. var morphInfluencers = 0;
  89364. if (manager) {
  89365. if (manager.numInfluencers > 0) {
  89366. defines.push("#define MORPHTARGETS");
  89367. morphInfluencers = manager.numInfluencers;
  89368. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  89369. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  89370. }
  89371. }
  89372. // Instances
  89373. if (useInstances) {
  89374. defines.push("#define INSTANCES");
  89375. attribs.push("world0");
  89376. attribs.push("world1");
  89377. attribs.push("world2");
  89378. attribs.push("world3");
  89379. }
  89380. // Get correct effect
  89381. var join = defines.join("\n");
  89382. if (this._cachedDefines !== join) {
  89383. this._cachedDefines = join;
  89384. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  89385. }
  89386. return this._effectLayerMapGenerationEffect.isReady();
  89387. };
  89388. /**
  89389. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  89390. */
  89391. EffectLayer.prototype.render = function () {
  89392. var currentEffect = this._mergeEffect;
  89393. // Check
  89394. if (!currentEffect.isReady())
  89395. return;
  89396. for (var i = 0; i < this._postProcesses.length; i++) {
  89397. if (!this._postProcesses[i].isReady()) {
  89398. return;
  89399. }
  89400. }
  89401. var engine = this._scene.getEngine();
  89402. this.onBeforeComposeObservable.notifyObservers(this);
  89403. // Render
  89404. engine.enableEffect(currentEffect);
  89405. engine.setState(false);
  89406. // VBOs
  89407. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89408. // Cache
  89409. var previousAlphaMode = engine.getAlphaMode();
  89410. // Go Blend.
  89411. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  89412. // Blends the map on the main canvas.
  89413. this._internalRender(currentEffect);
  89414. // Restore Alpha
  89415. engine.setAlphaMode(previousAlphaMode);
  89416. this.onAfterComposeObservable.notifyObservers(this);
  89417. // Handle size changes.
  89418. var size = this._mainTexture.getSize();
  89419. this._setMainTextureSize();
  89420. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  89421. // Recreate RTT and post processes on size change.
  89422. this.onSizeChangedObservable.notifyObservers(this);
  89423. this._disposeTextureAndPostProcesses();
  89424. this._createMainTexture();
  89425. this._createTextureAndPostProcesses();
  89426. }
  89427. };
  89428. /**
  89429. * Determine if a given mesh will be used in the current effect.
  89430. * @param mesh mesh to test
  89431. * @returns true if the mesh will be used
  89432. */
  89433. EffectLayer.prototype.hasMesh = function (mesh) {
  89434. return true;
  89435. };
  89436. /**
  89437. * Returns true if the layer contains information to display, otherwise false.
  89438. * @returns true if the glow layer should be rendered
  89439. */
  89440. EffectLayer.prototype.shouldRender = function () {
  89441. return this.isEnabled && this._shouldRender;
  89442. };
  89443. /**
  89444. * Returns true if the mesh should render, otherwise false.
  89445. * @param mesh The mesh to render
  89446. * @returns true if it should render otherwise false
  89447. */
  89448. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  89449. return true;
  89450. };
  89451. /**
  89452. * Returns true if the mesh should render, otherwise false.
  89453. * @param mesh The mesh to render
  89454. * @returns true if it should render otherwise false
  89455. */
  89456. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  89457. return true;
  89458. };
  89459. /**
  89460. * Renders the submesh passed in parameter to the generation map.
  89461. */
  89462. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  89463. var _this = this;
  89464. if (!this.shouldRender()) {
  89465. return;
  89466. }
  89467. var material = subMesh.getMaterial();
  89468. var mesh = subMesh.getRenderingMesh();
  89469. var scene = this._scene;
  89470. var engine = scene.getEngine();
  89471. if (!material) {
  89472. return;
  89473. }
  89474. // Do not block in blend mode.
  89475. if (material.needAlphaBlendingForMesh(mesh)) {
  89476. return;
  89477. }
  89478. // Culling
  89479. engine.setState(material.backFaceCulling);
  89480. // Managing instances
  89481. var batch = mesh._getInstancesRenderList(subMesh._id);
  89482. if (batch.mustReturn) {
  89483. return;
  89484. }
  89485. // Early Exit per mesh
  89486. if (!this._shouldRenderMesh(mesh)) {
  89487. return;
  89488. }
  89489. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  89490. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  89491. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  89492. engine.enableEffect(this._effectLayerMapGenerationEffect);
  89493. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  89494. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  89495. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  89496. // Alpha test
  89497. if (material && material.needAlphaTesting()) {
  89498. var alphaTexture = material.getAlphaTestTexture();
  89499. if (alphaTexture) {
  89500. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  89501. var textureMatrix = alphaTexture.getTextureMatrix();
  89502. if (textureMatrix) {
  89503. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  89504. }
  89505. }
  89506. }
  89507. // Glow emissive only
  89508. if (this._emissiveTextureAndColor.texture) {
  89509. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  89510. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  89511. }
  89512. // Bones
  89513. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89514. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89515. }
  89516. // Morph targets
  89517. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  89518. // Draw
  89519. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  89520. }
  89521. else {
  89522. // Need to reset refresh rate of the shadowMap
  89523. this._mainTexture.resetRefreshCounter();
  89524. }
  89525. };
  89526. /**
  89527. * Rebuild the required buffers.
  89528. * @ignore Internal use only.
  89529. */
  89530. EffectLayer.prototype._rebuild = function () {
  89531. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89532. if (vb) {
  89533. vb._rebuild();
  89534. }
  89535. this._generateIndexBuffer();
  89536. };
  89537. /**
  89538. * Dispose only the render target textures and post process.
  89539. */
  89540. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  89541. this._mainTexture.dispose();
  89542. for (var i = 0; i < this._postProcesses.length; i++) {
  89543. if (this._postProcesses[i]) {
  89544. this._postProcesses[i].dispose();
  89545. }
  89546. }
  89547. this._postProcesses = [];
  89548. for (var i = 0; i < this._textures.length; i++) {
  89549. if (this._textures[i]) {
  89550. this._textures[i].dispose();
  89551. }
  89552. }
  89553. this._textures = [];
  89554. };
  89555. /**
  89556. * Dispose the highlight layer and free resources.
  89557. */
  89558. EffectLayer.prototype.dispose = function () {
  89559. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89560. if (vertexBuffer) {
  89561. vertexBuffer.dispose();
  89562. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89563. }
  89564. if (this._indexBuffer) {
  89565. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89566. this._indexBuffer = null;
  89567. }
  89568. // Clean textures and post processes
  89569. this._disposeTextureAndPostProcesses();
  89570. // Remove from scene
  89571. var index = this._scene.effectLayers.indexOf(this, 0);
  89572. if (index > -1) {
  89573. this._scene.effectLayers.splice(index, 1);
  89574. }
  89575. // Callback
  89576. this.onDisposeObservable.notifyObservers(this);
  89577. this.onDisposeObservable.clear();
  89578. this.onBeforeRenderMainTextureObservable.clear();
  89579. this.onBeforeComposeObservable.clear();
  89580. this.onAfterComposeObservable.clear();
  89581. this.onSizeChangedObservable.clear();
  89582. };
  89583. /**
  89584. * Gets the class name of the effect layer
  89585. * @returns the string with the class name of the effect layer
  89586. */
  89587. EffectLayer.prototype.getClassName = function () {
  89588. return "EffectLayer";
  89589. };
  89590. /**
  89591. * Creates an effect layer from parsed effect layer data
  89592. * @param parsedEffectLayer defines effect layer data
  89593. * @param scene defines the current scene
  89594. * @param rootUrl defines the root URL containing the effect layer information
  89595. * @returns a parsed effect Layer
  89596. */
  89597. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  89598. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  89599. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  89600. };
  89601. __decorate([
  89602. BABYLON.serialize()
  89603. ], EffectLayer.prototype, "name", void 0);
  89604. __decorate([
  89605. BABYLON.serializeAsColor4()
  89606. ], EffectLayer.prototype, "neutralColor", void 0);
  89607. __decorate([
  89608. BABYLON.serialize()
  89609. ], EffectLayer.prototype, "isEnabled", void 0);
  89610. __decorate([
  89611. BABYLON.serializeAsCameraReference()
  89612. ], EffectLayer.prototype, "camera", null);
  89613. return EffectLayer;
  89614. }());
  89615. BABYLON.EffectLayer = EffectLayer;
  89616. })(BABYLON || (BABYLON = {}));
  89617. //# sourceMappingURL=babylon.effectLayer.js.map
  89618. "use strict";
  89619. var BABYLON;
  89620. (function (BABYLON) {
  89621. /**
  89622. * Special Glow Blur post process only blurring the alpha channel
  89623. * It enforces keeping the most luminous color in the color channel.
  89624. */
  89625. var GlowBlurPostProcess = /** @class */ (function (_super) {
  89626. __extends(GlowBlurPostProcess, _super);
  89627. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  89628. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89629. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  89630. _this.direction = direction;
  89631. _this.kernel = kernel;
  89632. _this.onApplyObservable.add(function (effect) {
  89633. effect.setFloat2("screenSize", _this.width, _this.height);
  89634. effect.setVector2("direction", _this.direction);
  89635. effect.setFloat("blurWidth", _this.kernel);
  89636. });
  89637. return _this;
  89638. }
  89639. return GlowBlurPostProcess;
  89640. }(BABYLON.PostProcess));
  89641. /**
  89642. * The highlight layer Helps adding a glow effect around a mesh.
  89643. *
  89644. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  89645. * glowy meshes to your scene.
  89646. *
  89647. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  89648. */
  89649. var HighlightLayer = /** @class */ (function (_super) {
  89650. __extends(HighlightLayer, _super);
  89651. /**
  89652. * Instantiates a new highlight Layer and references it to the scene..
  89653. * @param name The name of the layer
  89654. * @param scene The scene to use the layer in
  89655. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  89656. */
  89657. function HighlightLayer(name, scene, options) {
  89658. var _this = _super.call(this, name, scene) || this;
  89659. _this.name = name;
  89660. /**
  89661. * Specifies whether or not the inner glow is ACTIVE in the layer.
  89662. */
  89663. _this.innerGlow = true;
  89664. /**
  89665. * Specifies whether or not the outer glow is ACTIVE in the layer.
  89666. */
  89667. _this.outerGlow = true;
  89668. /**
  89669. * An event triggered when the highlight layer is being blurred.
  89670. */
  89671. _this.onBeforeBlurObservable = new BABYLON.Observable();
  89672. /**
  89673. * An event triggered when the highlight layer has been blurred.
  89674. */
  89675. _this.onAfterBlurObservable = new BABYLON.Observable();
  89676. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  89677. _this._meshes = {};
  89678. _this._excludedMeshes = {};
  89679. _this.neutralColor = HighlightLayer.NeutralColor;
  89680. // Warn on stencil
  89681. if (!_this._engine.isStencilEnable) {
  89682. 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 }");
  89683. }
  89684. // Adapt options
  89685. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  89686. // Initialize the layer
  89687. _this._init({
  89688. alphaBlendingMode: _this._options.alphaBlendingMode,
  89689. camera: _this._options.camera,
  89690. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  89691. mainTextureRatio: _this._options.mainTextureRatio
  89692. });
  89693. // Do not render as long as no meshes have been added
  89694. _this._shouldRender = false;
  89695. return _this;
  89696. }
  89697. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  89698. /**
  89699. * Gets the horizontal size of the blur.
  89700. */
  89701. get: function () {
  89702. return this._horizontalBlurPostprocess.kernel;
  89703. },
  89704. /**
  89705. * Specifies the horizontal size of the blur.
  89706. */
  89707. set: function (value) {
  89708. this._horizontalBlurPostprocess.kernel = value;
  89709. },
  89710. enumerable: true,
  89711. configurable: true
  89712. });
  89713. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  89714. /**
  89715. * Gets the vertical size of the blur.
  89716. */
  89717. get: function () {
  89718. return this._verticalBlurPostprocess.kernel;
  89719. },
  89720. /**
  89721. * Specifies the vertical size of the blur.
  89722. */
  89723. set: function (value) {
  89724. this._verticalBlurPostprocess.kernel = value;
  89725. },
  89726. enumerable: true,
  89727. configurable: true
  89728. });
  89729. /**
  89730. * Get the effect name of the layer.
  89731. * @return The effect name
  89732. */
  89733. HighlightLayer.prototype.getEffectName = function () {
  89734. return HighlightLayer.EffectName;
  89735. };
  89736. /**
  89737. * Create the merge effect. This is the shader use to blit the information back
  89738. * to the main canvas at the end of the scene rendering.
  89739. */
  89740. HighlightLayer.prototype._createMergeEffect = function () {
  89741. // Effect
  89742. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  89743. };
  89744. /**
  89745. * Creates the render target textures and post processes used in the highlight layer.
  89746. */
  89747. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  89748. var _this = this;
  89749. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  89750. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  89751. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  89752. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  89753. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  89754. width: blurTextureWidth,
  89755. height: blurTextureHeight
  89756. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89757. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89758. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89759. this._blurTexture.anisotropicFilteringLevel = 16;
  89760. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  89761. this._blurTexture.renderParticles = false;
  89762. this._blurTexture.ignoreCameraViewport = true;
  89763. this._textures = [this._blurTexture];
  89764. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  89765. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89766. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  89767. effect.setTexture("textureSampler", _this._mainTexture);
  89768. });
  89769. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89770. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  89771. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  89772. });
  89773. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89774. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  89775. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  89776. });
  89777. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  89778. }
  89779. else {
  89780. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  89781. width: blurTextureWidth,
  89782. height: blurTextureHeight
  89783. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89784. this._horizontalBlurPostprocess.width = blurTextureWidth;
  89785. this._horizontalBlurPostprocess.height = blurTextureHeight;
  89786. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  89787. effect.setTexture("textureSampler", _this._mainTexture);
  89788. });
  89789. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  89790. width: blurTextureWidth,
  89791. height: blurTextureHeight
  89792. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89793. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  89794. }
  89795. this._mainTexture.onAfterUnbindObservable.add(function () {
  89796. _this.onBeforeBlurObservable.notifyObservers(_this);
  89797. var internalTexture = _this._blurTexture.getInternalTexture();
  89798. if (internalTexture) {
  89799. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  89800. }
  89801. _this.onAfterBlurObservable.notifyObservers(_this);
  89802. });
  89803. // Prevent autoClear.
  89804. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  89805. };
  89806. /**
  89807. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  89808. */
  89809. HighlightLayer.prototype.needStencil = function () {
  89810. return true;
  89811. };
  89812. /**
  89813. * Checks for the readiness of the element composing the layer.
  89814. * @param subMesh the mesh to check for
  89815. * @param useInstances specify wether or not to use instances to render the mesh
  89816. * @param emissiveTexture the associated emissive texture used to generate the glow
  89817. * @return true if ready otherwise, false
  89818. */
  89819. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  89820. var material = subMesh.getMaterial();
  89821. var mesh = subMesh.getRenderingMesh();
  89822. if (!material || !mesh || !this._meshes) {
  89823. return false;
  89824. }
  89825. var emissiveTexture = null;
  89826. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  89827. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  89828. emissiveTexture = material.emissiveTexture;
  89829. }
  89830. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  89831. };
  89832. /**
  89833. * Implementation specific of rendering the generating effect on the main canvas.
  89834. * @param effect The effect used to render through
  89835. */
  89836. HighlightLayer.prototype._internalRender = function (effect) {
  89837. // Texture
  89838. effect.setTexture("textureSampler", this._blurTexture);
  89839. // Cache
  89840. var engine = this._engine;
  89841. var previousStencilBuffer = engine.getStencilBuffer();
  89842. var previousStencilFunction = engine.getStencilFunction();
  89843. var previousStencilMask = engine.getStencilMask();
  89844. var previousStencilOperationPass = engine.getStencilOperationPass();
  89845. var previousStencilOperationFail = engine.getStencilOperationFail();
  89846. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  89847. var previousStencilReference = engine.getStencilFunctionReference();
  89848. // Stencil operations
  89849. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  89850. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  89851. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  89852. // Draw order
  89853. engine.setStencilMask(0x00);
  89854. engine.setStencilBuffer(true);
  89855. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  89856. // 2 passes inner outer
  89857. if (this.outerGlow) {
  89858. effect.setFloat("offset", 0);
  89859. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  89860. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89861. }
  89862. if (this.innerGlow) {
  89863. effect.setFloat("offset", 1);
  89864. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  89865. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89866. }
  89867. // Restore Cache
  89868. engine.setStencilFunction(previousStencilFunction);
  89869. engine.setStencilMask(previousStencilMask);
  89870. engine.setStencilBuffer(previousStencilBuffer);
  89871. engine.setStencilOperationPass(previousStencilOperationPass);
  89872. engine.setStencilOperationFail(previousStencilOperationFail);
  89873. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  89874. engine.setStencilFunctionReference(previousStencilReference);
  89875. };
  89876. /**
  89877. * Returns true if the layer contains information to display, otherwise false.
  89878. */
  89879. HighlightLayer.prototype.shouldRender = function () {
  89880. if (_super.prototype.shouldRender.call(this)) {
  89881. return this._meshes ? true : false;
  89882. }
  89883. return false;
  89884. };
  89885. /**
  89886. * Returns true if the mesh should render, otherwise false.
  89887. * @param mesh The mesh to render
  89888. * @returns true if it should render otherwise false
  89889. */
  89890. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  89891. // Excluded Mesh
  89892. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  89893. return false;
  89894. }
  89895. ;
  89896. return true;
  89897. };
  89898. /**
  89899. * Sets the required values for both the emissive texture and and the main color.
  89900. */
  89901. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  89902. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  89903. if (highlightLayerMesh) {
  89904. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  89905. }
  89906. else {
  89907. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  89908. }
  89909. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  89910. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  89911. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  89912. }
  89913. else {
  89914. this._emissiveTextureAndColor.texture = null;
  89915. }
  89916. };
  89917. /**
  89918. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  89919. * @param mesh The mesh to exclude from the highlight layer
  89920. */
  89921. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  89922. if (!this._excludedMeshes) {
  89923. return;
  89924. }
  89925. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  89926. if (!meshExcluded) {
  89927. this._excludedMeshes[mesh.uniqueId] = {
  89928. mesh: mesh,
  89929. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  89930. mesh.getEngine().setStencilBuffer(false);
  89931. }),
  89932. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  89933. mesh.getEngine().setStencilBuffer(true);
  89934. }),
  89935. };
  89936. }
  89937. };
  89938. /**
  89939. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  89940. * @param mesh The mesh to highlight
  89941. */
  89942. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  89943. if (!this._excludedMeshes) {
  89944. return;
  89945. }
  89946. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  89947. if (meshExcluded) {
  89948. if (meshExcluded.beforeRender) {
  89949. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  89950. }
  89951. if (meshExcluded.afterRender) {
  89952. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  89953. }
  89954. }
  89955. this._excludedMeshes[mesh.uniqueId] = null;
  89956. };
  89957. /**
  89958. * Determine if a given mesh will be highlighted by the current HighlightLayer
  89959. * @param mesh mesh to test
  89960. * @returns true if the mesh will be highlighted by the current HighlightLayer
  89961. */
  89962. HighlightLayer.prototype.hasMesh = function (mesh) {
  89963. if (!this._meshes) {
  89964. return false;
  89965. }
  89966. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  89967. };
  89968. /**
  89969. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  89970. * @param mesh The mesh to highlight
  89971. * @param color The color of the highlight
  89972. * @param glowEmissiveOnly Extract the glow from the emissive texture
  89973. */
  89974. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  89975. var _this = this;
  89976. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  89977. if (!this._meshes) {
  89978. return;
  89979. }
  89980. var meshHighlight = this._meshes[mesh.uniqueId];
  89981. if (meshHighlight) {
  89982. meshHighlight.color = color;
  89983. }
  89984. else {
  89985. this._meshes[mesh.uniqueId] = {
  89986. mesh: mesh,
  89987. color: color,
  89988. // Lambda required for capture due to Observable this context
  89989. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  89990. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  89991. _this._defaultStencilReference(mesh);
  89992. }
  89993. else {
  89994. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  89995. }
  89996. }),
  89997. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  89998. glowEmissiveOnly: glowEmissiveOnly
  89999. };
  90000. }
  90001. this._shouldRender = true;
  90002. };
  90003. /**
  90004. * Remove a mesh from the highlight layer in order to make it stop glowing.
  90005. * @param mesh The mesh to highlight
  90006. */
  90007. HighlightLayer.prototype.removeMesh = function (mesh) {
  90008. if (!this._meshes) {
  90009. return;
  90010. }
  90011. var meshHighlight = this._meshes[mesh.uniqueId];
  90012. if (meshHighlight) {
  90013. if (meshHighlight.observerHighlight) {
  90014. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  90015. }
  90016. if (meshHighlight.observerDefault) {
  90017. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  90018. }
  90019. delete this._meshes[mesh.uniqueId];
  90020. }
  90021. this._shouldRender = false;
  90022. for (var meshHighlightToCheck in this._meshes) {
  90023. if (this._meshes[meshHighlightToCheck]) {
  90024. this._shouldRender = true;
  90025. break;
  90026. }
  90027. }
  90028. };
  90029. /**
  90030. * Force the stencil to the normal expected value for none glowing parts
  90031. */
  90032. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  90033. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  90034. };
  90035. /**
  90036. * Free any resources and references associated to a mesh.
  90037. * Internal use
  90038. * @param mesh The mesh to free.
  90039. */
  90040. HighlightLayer.prototype._disposeMesh = function (mesh) {
  90041. this.removeMesh(mesh);
  90042. this.removeExcludedMesh(mesh);
  90043. };
  90044. /**
  90045. * Dispose the highlight layer and free resources.
  90046. */
  90047. HighlightLayer.prototype.dispose = function () {
  90048. if (this._meshes) {
  90049. // Clean mesh references
  90050. for (var id in this._meshes) {
  90051. var meshHighlight = this._meshes[id];
  90052. if (meshHighlight && meshHighlight.mesh) {
  90053. if (meshHighlight.observerHighlight) {
  90054. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  90055. }
  90056. if (meshHighlight.observerDefault) {
  90057. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  90058. }
  90059. }
  90060. }
  90061. this._meshes = null;
  90062. }
  90063. if (this._excludedMeshes) {
  90064. for (var id in this._excludedMeshes) {
  90065. var meshHighlight = this._excludedMeshes[id];
  90066. if (meshHighlight) {
  90067. if (meshHighlight.beforeRender) {
  90068. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  90069. }
  90070. if (meshHighlight.afterRender) {
  90071. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  90072. }
  90073. }
  90074. }
  90075. this._excludedMeshes = null;
  90076. }
  90077. _super.prototype.dispose.call(this);
  90078. };
  90079. /**
  90080. * Gets the class name of the effect layer
  90081. * @returns the string with the class name of the effect layer
  90082. */
  90083. HighlightLayer.prototype.getClassName = function () {
  90084. return "HighlightLayer";
  90085. };
  90086. /**
  90087. * Serializes this Highlight layer
  90088. * @returns a serialized Highlight layer object
  90089. */
  90090. HighlightLayer.prototype.serialize = function () {
  90091. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90092. serializationObject.customType = "BABYLON.HighlightLayer";
  90093. // Highlighted meshes
  90094. serializationObject.meshes = [];
  90095. if (this._meshes) {
  90096. for (var m in this._meshes) {
  90097. var mesh = this._meshes[m];
  90098. if (mesh) {
  90099. serializationObject.meshes.push({
  90100. glowEmissiveOnly: mesh.glowEmissiveOnly,
  90101. color: mesh.color.asArray(),
  90102. meshId: mesh.mesh.id
  90103. });
  90104. }
  90105. }
  90106. }
  90107. // Excluded meshes
  90108. serializationObject.excludedMeshes = [];
  90109. if (this._excludedMeshes) {
  90110. for (var e in this._excludedMeshes) {
  90111. var excludedMesh = this._excludedMeshes[e];
  90112. if (excludedMesh) {
  90113. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  90114. }
  90115. }
  90116. }
  90117. return serializationObject;
  90118. };
  90119. /**
  90120. * Creates a Highlight layer from parsed Highlight layer data
  90121. * @param parsedHightlightLayer defines the Highlight layer data
  90122. * @param scene defines the current scene
  90123. * @param rootUrl defines the root URL containing the Highlight layer information
  90124. * @returns a parsed Highlight layer
  90125. */
  90126. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  90127. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  90128. var index;
  90129. // Excluded meshes
  90130. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  90131. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  90132. if (mesh) {
  90133. hl.addExcludedMesh(mesh);
  90134. }
  90135. }
  90136. // Included meshes
  90137. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  90138. var highlightedMesh = parsedHightlightLayer.meshes[index];
  90139. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  90140. if (mesh) {
  90141. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  90142. }
  90143. }
  90144. return hl;
  90145. };
  90146. /**
  90147. * Effect Name of the highlight layer.
  90148. */
  90149. HighlightLayer.EffectName = "HighlightLayer";
  90150. /**
  90151. * The neutral color used during the preparation of the glow effect.
  90152. * This is black by default as the blend operation is a blend operation.
  90153. */
  90154. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  90155. /**
  90156. * Stencil value used for glowing meshes.
  90157. */
  90158. HighlightLayer.GlowingMeshStencilReference = 0x02;
  90159. /**
  90160. * Stencil value used for the other meshes in the scene.
  90161. */
  90162. HighlightLayer.NormalMeshStencilReference = 0x01;
  90163. __decorate([
  90164. BABYLON.serialize()
  90165. ], HighlightLayer.prototype, "innerGlow", void 0);
  90166. __decorate([
  90167. BABYLON.serialize()
  90168. ], HighlightLayer.prototype, "outerGlow", void 0);
  90169. __decorate([
  90170. BABYLON.serialize()
  90171. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  90172. __decorate([
  90173. BABYLON.serialize()
  90174. ], HighlightLayer.prototype, "blurVerticalSize", null);
  90175. __decorate([
  90176. BABYLON.serialize("options")
  90177. ], HighlightLayer.prototype, "_options", void 0);
  90178. return HighlightLayer;
  90179. }(BABYLON.EffectLayer));
  90180. BABYLON.HighlightLayer = HighlightLayer;
  90181. })(BABYLON || (BABYLON = {}));
  90182. //# sourceMappingURL=babylon.highlightLayer.js.map
  90183. "use strict";
  90184. var BABYLON;
  90185. (function (BABYLON) {
  90186. /**
  90187. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  90188. *
  90189. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  90190. * glowy meshes to your scene.
  90191. *
  90192. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  90193. */
  90194. var GlowLayer = /** @class */ (function (_super) {
  90195. __extends(GlowLayer, _super);
  90196. /**
  90197. * Instantiates a new glow Layer and references it to the scene.
  90198. * @param name The name of the layer
  90199. * @param scene The scene to use the layer in
  90200. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  90201. */
  90202. function GlowLayer(name, scene, options) {
  90203. var _this = _super.call(this, name, scene) || this;
  90204. _this._intensity = 1.0;
  90205. _this._includedOnlyMeshes = [];
  90206. _this._excludedMeshes = [];
  90207. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  90208. // Adapt options
  90209. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  90210. // Initialize the layer
  90211. _this._init({
  90212. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  90213. camera: _this._options.camera,
  90214. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  90215. mainTextureRatio: _this._options.mainTextureRatio
  90216. });
  90217. return _this;
  90218. }
  90219. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  90220. /**
  90221. * Gets the kernel size of the blur.
  90222. */
  90223. get: function () {
  90224. return this._horizontalBlurPostprocess1.kernel;
  90225. },
  90226. /**
  90227. * Sets the kernel size of the blur.
  90228. */
  90229. set: function (value) {
  90230. this._horizontalBlurPostprocess1.kernel = value;
  90231. this._verticalBlurPostprocess1.kernel = value;
  90232. this._horizontalBlurPostprocess2.kernel = value;
  90233. this._verticalBlurPostprocess2.kernel = value;
  90234. },
  90235. enumerable: true,
  90236. configurable: true
  90237. });
  90238. Object.defineProperty(GlowLayer.prototype, "intensity", {
  90239. /**
  90240. * Gets the glow intensity.
  90241. */
  90242. get: function () {
  90243. return this._intensity;
  90244. },
  90245. /**
  90246. * Sets the glow intensity.
  90247. */
  90248. set: function (value) {
  90249. this._intensity = value;
  90250. },
  90251. enumerable: true,
  90252. configurable: true
  90253. });
  90254. /**
  90255. * Get the effect name of the layer.
  90256. * @return The effect name
  90257. */
  90258. GlowLayer.prototype.getEffectName = function () {
  90259. return GlowLayer.EffectName;
  90260. };
  90261. /**
  90262. * Create the merge effect. This is the shader use to blit the information back
  90263. * to the main canvas at the end of the scene rendering.
  90264. */
  90265. GlowLayer.prototype._createMergeEffect = function () {
  90266. // Effect
  90267. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  90268. };
  90269. /**
  90270. * Creates the render target textures and post processes used in the glow layer.
  90271. */
  90272. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  90273. var _this = this;
  90274. var blurTextureWidth = this._mainTextureDesiredSize.width;
  90275. var blurTextureHeight = this._mainTextureDesiredSize.height;
  90276. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  90277. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  90278. var textureType = 0;
  90279. if (this._engine.getCaps().textureHalfFloatRender) {
  90280. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90281. }
  90282. else {
  90283. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90284. }
  90285. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  90286. width: blurTextureWidth,
  90287. height: blurTextureHeight
  90288. }, this._scene, false, true, textureType);
  90289. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90290. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90291. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90292. this._blurTexture1.renderParticles = false;
  90293. this._blurTexture1.ignoreCameraViewport = true;
  90294. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  90295. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  90296. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  90297. width: blurTextureWidth2,
  90298. height: blurTextureHeight2
  90299. }, this._scene, false, true, textureType);
  90300. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90301. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90302. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90303. this._blurTexture2.renderParticles = false;
  90304. this._blurTexture2.ignoreCameraViewport = true;
  90305. this._textures = [this._blurTexture1, this._blurTexture2];
  90306. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  90307. width: blurTextureWidth,
  90308. height: blurTextureHeight
  90309. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90310. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  90311. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  90312. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  90313. effect.setTexture("textureSampler", _this._mainTexture);
  90314. });
  90315. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  90316. width: blurTextureWidth,
  90317. height: blurTextureHeight
  90318. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90319. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  90320. width: blurTextureWidth2,
  90321. height: blurTextureHeight2
  90322. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90323. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  90324. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  90325. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  90326. effect.setTexture("textureSampler", _this._blurTexture1);
  90327. });
  90328. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  90329. width: blurTextureWidth2,
  90330. height: blurTextureHeight2
  90331. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90332. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  90333. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  90334. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  90335. this._mainTexture.samples = this._options.mainTextureSamples;
  90336. this._mainTexture.onAfterUnbindObservable.add(function () {
  90337. var internalTexture = _this._blurTexture1.getInternalTexture();
  90338. if (internalTexture) {
  90339. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  90340. internalTexture = _this._blurTexture2.getInternalTexture();
  90341. if (internalTexture) {
  90342. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  90343. }
  90344. }
  90345. });
  90346. // Prevent autoClear.
  90347. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  90348. };
  90349. /**
  90350. * Checks for the readiness of the element composing the layer.
  90351. * @param subMesh the mesh to check for
  90352. * @param useInstances specify wether or not to use instances to render the mesh
  90353. * @param emissiveTexture the associated emissive texture used to generate the glow
  90354. * @return true if ready otherwise, false
  90355. */
  90356. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  90357. var material = subMesh.getMaterial();
  90358. var mesh = subMesh.getRenderingMesh();
  90359. if (!material || !mesh) {
  90360. return false;
  90361. }
  90362. var emissiveTexture = material.emissiveTexture;
  90363. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  90364. };
  90365. /**
  90366. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  90367. */
  90368. GlowLayer.prototype.needStencil = function () {
  90369. return false;
  90370. };
  90371. /**
  90372. * Implementation specific of rendering the generating effect on the main canvas.
  90373. * @param effect The effect used to render through
  90374. */
  90375. GlowLayer.prototype._internalRender = function (effect) {
  90376. // Texture
  90377. effect.setTexture("textureSampler", this._blurTexture1);
  90378. effect.setTexture("textureSampler2", this._blurTexture2);
  90379. effect.setFloat("offset", this._intensity);
  90380. // Cache
  90381. var engine = this._engine;
  90382. var previousStencilBuffer = engine.getStencilBuffer();
  90383. // Draw order
  90384. engine.setStencilBuffer(false);
  90385. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90386. // Draw order
  90387. engine.setStencilBuffer(previousStencilBuffer);
  90388. };
  90389. /**
  90390. * Sets the required values for both the emissive texture and and the main color.
  90391. */
  90392. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  90393. var textureLevel = 1.0;
  90394. if (this.customEmissiveTextureSelector) {
  90395. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  90396. }
  90397. else {
  90398. if (material) {
  90399. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  90400. if (this._emissiveTextureAndColor.texture) {
  90401. textureLevel = this._emissiveTextureAndColor.texture.level;
  90402. }
  90403. }
  90404. else {
  90405. this._emissiveTextureAndColor.texture = null;
  90406. }
  90407. }
  90408. if (this.customEmissiveColorSelector) {
  90409. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  90410. }
  90411. else {
  90412. if (material.emissiveColor) {
  90413. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  90414. }
  90415. else {
  90416. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  90417. }
  90418. }
  90419. };
  90420. /**
  90421. * Returns true if the mesh should render, otherwise false.
  90422. * @param mesh The mesh to render
  90423. * @returns true if it should render otherwise false
  90424. */
  90425. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  90426. return this.hasMesh(mesh);
  90427. };
  90428. /**
  90429. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  90430. * @param mesh The mesh to exclude from the glow layer
  90431. */
  90432. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  90433. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  90434. this._excludedMeshes.push(mesh.uniqueId);
  90435. }
  90436. };
  90437. /**
  90438. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  90439. * @param mesh The mesh to remove
  90440. */
  90441. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  90442. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  90443. if (index !== -1) {
  90444. this._excludedMeshes.splice(index, 1);
  90445. }
  90446. };
  90447. /**
  90448. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  90449. * @param mesh The mesh to include in the glow layer
  90450. */
  90451. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  90452. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  90453. this._includedOnlyMeshes.push(mesh.uniqueId);
  90454. }
  90455. };
  90456. /**
  90457. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  90458. * @param mesh The mesh to remove
  90459. */
  90460. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  90461. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  90462. if (index !== -1) {
  90463. this._includedOnlyMeshes.splice(index, 1);
  90464. }
  90465. };
  90466. /**
  90467. * Determine if a given mesh will be used in the glow layer
  90468. * @param mesh The mesh to test
  90469. * @returns true if the mesh will be highlighted by the current glow layer
  90470. */
  90471. GlowLayer.prototype.hasMesh = function (mesh) {
  90472. // Included Mesh
  90473. if (this._includedOnlyMeshes.length) {
  90474. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  90475. }
  90476. ;
  90477. // Excluded Mesh
  90478. if (this._excludedMeshes.length) {
  90479. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  90480. }
  90481. ;
  90482. return true;
  90483. };
  90484. /**
  90485. * Free any resources and references associated to a mesh.
  90486. * Internal use
  90487. * @param mesh The mesh to free.
  90488. */
  90489. GlowLayer.prototype._disposeMesh = function (mesh) {
  90490. this.removeIncludedOnlyMesh(mesh);
  90491. this.removeExcludedMesh(mesh);
  90492. };
  90493. /**
  90494. * Gets the class name of the effect layer
  90495. * @returns the string with the class name of the effect layer
  90496. */
  90497. GlowLayer.prototype.getClassName = function () {
  90498. return "GlowLayer";
  90499. };
  90500. /**
  90501. * Serializes this glow layer
  90502. * @returns a serialized glow layer object
  90503. */
  90504. GlowLayer.prototype.serialize = function () {
  90505. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90506. serializationObject.customType = "BABYLON.GlowLayer";
  90507. var index;
  90508. // Included meshes
  90509. serializationObject.includedMeshes = [];
  90510. if (this._includedOnlyMeshes.length) {
  90511. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  90512. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  90513. if (mesh) {
  90514. serializationObject.includedMeshes.push(mesh.id);
  90515. }
  90516. }
  90517. }
  90518. // Excluded meshes
  90519. serializationObject.excludedMeshes = [];
  90520. if (this._excludedMeshes.length) {
  90521. for (index = 0; index < this._excludedMeshes.length; index++) {
  90522. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  90523. if (mesh) {
  90524. serializationObject.excludedMeshes.push(mesh.id);
  90525. }
  90526. }
  90527. }
  90528. return serializationObject;
  90529. };
  90530. /**
  90531. * Creates a Glow Layer from parsed glow layer data
  90532. * @param parsedGlowLayer defines glow layer data
  90533. * @param scene defines the current scene
  90534. * @param rootUrl defines the root URL containing the glow layer information
  90535. * @returns a parsed Glow Layer
  90536. */
  90537. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  90538. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  90539. var index;
  90540. // Excluded meshes
  90541. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  90542. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  90543. if (mesh) {
  90544. gl.addExcludedMesh(mesh);
  90545. }
  90546. }
  90547. // Included meshes
  90548. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  90549. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  90550. if (mesh) {
  90551. gl.addIncludedOnlyMesh(mesh);
  90552. }
  90553. }
  90554. return gl;
  90555. };
  90556. /**
  90557. * Effect Name of the layer.
  90558. */
  90559. GlowLayer.EffectName = "GlowLayer";
  90560. /**
  90561. * The default blur kernel size used for the glow.
  90562. */
  90563. GlowLayer.DefaultBlurKernelSize = 32;
  90564. /**
  90565. * The default texture size ratio used for the glow.
  90566. */
  90567. GlowLayer.DefaultTextureRatio = 0.5;
  90568. __decorate([
  90569. BABYLON.serialize()
  90570. ], GlowLayer.prototype, "blurKernelSize", null);
  90571. __decorate([
  90572. BABYLON.serialize()
  90573. ], GlowLayer.prototype, "intensity", null);
  90574. __decorate([
  90575. BABYLON.serialize("options")
  90576. ], GlowLayer.prototype, "_options", void 0);
  90577. return GlowLayer;
  90578. }(BABYLON.EffectLayer));
  90579. BABYLON.GlowLayer = GlowLayer;
  90580. })(BABYLON || (BABYLON = {}));
  90581. //# sourceMappingURL=babylon.glowLayer.js.map
  90582. "use strict";
  90583. var BABYLON;
  90584. (function (BABYLON) {
  90585. /**
  90586. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  90587. */
  90588. var AssetTaskState;
  90589. (function (AssetTaskState) {
  90590. /**
  90591. * Initialization
  90592. */
  90593. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  90594. /**
  90595. * Running
  90596. */
  90597. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  90598. /**
  90599. * Done
  90600. */
  90601. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  90602. /**
  90603. * Error
  90604. */
  90605. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  90606. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  90607. /**
  90608. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  90609. */
  90610. var AbstractAssetTask = /** @class */ (function () {
  90611. /**
  90612. * Creates a new {BABYLON.AssetsManager}
  90613. * @param name defines the name of the task
  90614. */
  90615. function AbstractAssetTask(
  90616. /**
  90617. * Task name
  90618. */ name) {
  90619. this.name = name;
  90620. this._isCompleted = false;
  90621. this._taskState = AssetTaskState.INIT;
  90622. }
  90623. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  90624. /**
  90625. * Get if the task is completed
  90626. */
  90627. get: function () {
  90628. return this._isCompleted;
  90629. },
  90630. enumerable: true,
  90631. configurable: true
  90632. });
  90633. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  90634. /**
  90635. * Gets the current state of the task
  90636. */
  90637. get: function () {
  90638. return this._taskState;
  90639. },
  90640. enumerable: true,
  90641. configurable: true
  90642. });
  90643. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  90644. /**
  90645. * Gets the current error object (if task is in error)
  90646. */
  90647. get: function () {
  90648. return this._errorObject;
  90649. },
  90650. enumerable: true,
  90651. configurable: true
  90652. });
  90653. /**
  90654. * Internal only
  90655. * @ignore
  90656. */
  90657. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  90658. if (this._errorObject) {
  90659. return;
  90660. }
  90661. this._errorObject = {
  90662. message: message,
  90663. exception: exception
  90664. };
  90665. };
  90666. /**
  90667. * Execute the current task
  90668. * @param scene defines the scene where you want your assets to be loaded
  90669. * @param onSuccess is a callback called when the task is successfully executed
  90670. * @param onError is a callback called if an error occurs
  90671. */
  90672. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  90673. var _this = this;
  90674. this._taskState = AssetTaskState.RUNNING;
  90675. this.runTask(scene, function () {
  90676. _this.onDoneCallback(onSuccess, onError);
  90677. }, function (msg, exception) {
  90678. _this.onErrorCallback(onError, msg, exception);
  90679. });
  90680. };
  90681. /**
  90682. * Execute the current task
  90683. * @param scene defines the scene where you want your assets to be loaded
  90684. * @param onSuccess is a callback called when the task is successfully executed
  90685. * @param onError is a callback called if an error occurs
  90686. */
  90687. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90688. throw new Error("runTask is not implemented");
  90689. };
  90690. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  90691. this._taskState = AssetTaskState.ERROR;
  90692. this._errorObject = {
  90693. message: message,
  90694. exception: exception
  90695. };
  90696. if (this.onError) {
  90697. this.onError(this, message, exception);
  90698. }
  90699. onError();
  90700. };
  90701. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  90702. try {
  90703. this._taskState = AssetTaskState.DONE;
  90704. this._isCompleted = true;
  90705. if (this.onSuccess) {
  90706. this.onSuccess(this);
  90707. }
  90708. onSuccess();
  90709. }
  90710. catch (e) {
  90711. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  90712. }
  90713. };
  90714. return AbstractAssetTask;
  90715. }());
  90716. BABYLON.AbstractAssetTask = AbstractAssetTask;
  90717. /**
  90718. * Class used to share progress information about assets loading
  90719. */
  90720. var AssetsProgressEvent = /** @class */ (function () {
  90721. /**
  90722. * Creates a {BABYLON.AssetsProgressEvent}
  90723. * @param remainingCount defines the number of remaining tasks to process
  90724. * @param totalCount defines the total number of tasks
  90725. * @param task defines the task that was just processed
  90726. */
  90727. function AssetsProgressEvent(remainingCount, totalCount, task) {
  90728. this.remainingCount = remainingCount;
  90729. this.totalCount = totalCount;
  90730. this.task = task;
  90731. }
  90732. return AssetsProgressEvent;
  90733. }());
  90734. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  90735. /**
  90736. * Define a task used by {BABYLON.AssetsManager} to load meshes
  90737. */
  90738. var MeshAssetTask = /** @class */ (function (_super) {
  90739. __extends(MeshAssetTask, _super);
  90740. /**
  90741. * Creates a new {BABYLON.MeshAssetTask}
  90742. * @param name defines the name of the task
  90743. * @param meshesNames defines the list of mesh's names you want to load
  90744. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  90745. * @param sceneFilename defines the filename of the scene to load from
  90746. */
  90747. function MeshAssetTask(
  90748. /**
  90749. * Defines the name of the task
  90750. */
  90751. name,
  90752. /**
  90753. * Defines the list of mesh's names you want to load
  90754. */
  90755. meshesNames,
  90756. /**
  90757. * Defines the root url to use as a base to load your meshes and associated resources
  90758. */
  90759. rootUrl,
  90760. /**
  90761. * Defines the filename of the scene to load from
  90762. */
  90763. sceneFilename) {
  90764. var _this = _super.call(this, name) || this;
  90765. _this.name = name;
  90766. _this.meshesNames = meshesNames;
  90767. _this.rootUrl = rootUrl;
  90768. _this.sceneFilename = sceneFilename;
  90769. return _this;
  90770. }
  90771. /**
  90772. * Execute the current task
  90773. * @param scene defines the scene where you want your assets to be loaded
  90774. * @param onSuccess is a callback called when the task is successfully executed
  90775. * @param onError is a callback called if an error occurs
  90776. */
  90777. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90778. var _this = this;
  90779. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  90780. _this.loadedMeshes = meshes;
  90781. _this.loadedParticleSystems = particleSystems;
  90782. _this.loadedSkeletons = skeletons;
  90783. onSuccess();
  90784. }, null, function (scene, message, exception) {
  90785. onError(message, exception);
  90786. });
  90787. };
  90788. return MeshAssetTask;
  90789. }(AbstractAssetTask));
  90790. BABYLON.MeshAssetTask = MeshAssetTask;
  90791. /**
  90792. * Define a task used by {BABYLON.AssetsManager} to load text content
  90793. */
  90794. var TextFileAssetTask = /** @class */ (function (_super) {
  90795. __extends(TextFileAssetTask, _super);
  90796. /**
  90797. * Creates a new TextFileAssetTask object
  90798. * @param name defines the name of the task
  90799. * @param url defines the location of the file to load
  90800. */
  90801. function TextFileAssetTask(
  90802. /**
  90803. * Defines the name of the task
  90804. */
  90805. name,
  90806. /**
  90807. * Defines the location of the file to load
  90808. */
  90809. url) {
  90810. var _this = _super.call(this, name) || this;
  90811. _this.name = name;
  90812. _this.url = url;
  90813. return _this;
  90814. }
  90815. /**
  90816. * Execute the current task
  90817. * @param scene defines the scene where you want your assets to be loaded
  90818. * @param onSuccess is a callback called when the task is successfully executed
  90819. * @param onError is a callback called if an error occurs
  90820. */
  90821. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90822. var _this = this;
  90823. scene._loadFile(this.url, function (data) {
  90824. _this.text = data;
  90825. onSuccess();
  90826. }, undefined, false, false, function (request, exception) {
  90827. if (request) {
  90828. onError(request.status + " " + request.statusText, exception);
  90829. }
  90830. });
  90831. };
  90832. return TextFileAssetTask;
  90833. }(AbstractAssetTask));
  90834. BABYLON.TextFileAssetTask = TextFileAssetTask;
  90835. /**
  90836. * Define a task used by {BABYLON.AssetsManager} to load binary data
  90837. */
  90838. var BinaryFileAssetTask = /** @class */ (function (_super) {
  90839. __extends(BinaryFileAssetTask, _super);
  90840. /**
  90841. * Creates a new BinaryFileAssetTask object
  90842. * @param name defines the name of the new task
  90843. * @param url defines the location of the file to load
  90844. */
  90845. function BinaryFileAssetTask(
  90846. /**
  90847. * Defines the name of the task
  90848. */
  90849. name,
  90850. /**
  90851. * Defines the location of the file to load
  90852. */
  90853. url) {
  90854. var _this = _super.call(this, name) || this;
  90855. _this.name = name;
  90856. _this.url = url;
  90857. return _this;
  90858. }
  90859. /**
  90860. * Execute the current task
  90861. * @param scene defines the scene where you want your assets to be loaded
  90862. * @param onSuccess is a callback called when the task is successfully executed
  90863. * @param onError is a callback called if an error occurs
  90864. */
  90865. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90866. var _this = this;
  90867. scene._loadFile(this.url, function (data) {
  90868. _this.data = data;
  90869. onSuccess();
  90870. }, undefined, true, true, function (request, exception) {
  90871. if (request) {
  90872. onError(request.status + " " + request.statusText, exception);
  90873. }
  90874. });
  90875. };
  90876. return BinaryFileAssetTask;
  90877. }(AbstractAssetTask));
  90878. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  90879. /**
  90880. * Define a task used by {BABYLON.AssetsManager} to load images
  90881. */
  90882. var ImageAssetTask = /** @class */ (function (_super) {
  90883. __extends(ImageAssetTask, _super);
  90884. /**
  90885. * Creates a new ImageAssetTask
  90886. * @param name defines the name of the task
  90887. * @param url defines the location of the image to load
  90888. */
  90889. function ImageAssetTask(
  90890. /**
  90891. * Defines the name of the task
  90892. */
  90893. name,
  90894. /**
  90895. * Defines the location of the image to load
  90896. */
  90897. url) {
  90898. var _this = _super.call(this, name) || this;
  90899. _this.name = name;
  90900. _this.url = url;
  90901. return _this;
  90902. }
  90903. /**
  90904. * Execute the current task
  90905. * @param scene defines the scene where you want your assets to be loaded
  90906. * @param onSuccess is a callback called when the task is successfully executed
  90907. * @param onError is a callback called if an error occurs
  90908. */
  90909. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90910. var _this = this;
  90911. var img = new Image();
  90912. BABYLON.Tools.SetCorsBehavior(this.url, img);
  90913. img.onload = function () {
  90914. _this.image = img;
  90915. onSuccess();
  90916. };
  90917. img.onerror = function (err) {
  90918. onError("Error loading image", err);
  90919. };
  90920. img.src = this.url;
  90921. };
  90922. return ImageAssetTask;
  90923. }(AbstractAssetTask));
  90924. BABYLON.ImageAssetTask = ImageAssetTask;
  90925. /**
  90926. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  90927. */
  90928. var TextureAssetTask = /** @class */ (function (_super) {
  90929. __extends(TextureAssetTask, _super);
  90930. /**
  90931. * Creates a new TextureAssetTask object
  90932. * @param name defines the name of the task
  90933. * @param url defines the location of the file to load
  90934. * @param noMipmap defines if mipmap should not be generated (default is false)
  90935. * @param invertY defines if texture must be inverted on Y axis (default is false)
  90936. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  90937. */
  90938. function TextureAssetTask(
  90939. /**
  90940. * Defines the name of the task
  90941. */
  90942. name,
  90943. /**
  90944. * Defines the location of the file to load
  90945. */
  90946. url,
  90947. /**
  90948. * Defines if mipmap should not be generated (default is false)
  90949. */
  90950. noMipmap,
  90951. /**
  90952. * Defines if texture must be inverted on Y axis (default is false)
  90953. */
  90954. invertY,
  90955. /**
  90956. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  90957. */
  90958. samplingMode) {
  90959. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90960. var _this = _super.call(this, name) || this;
  90961. _this.name = name;
  90962. _this.url = url;
  90963. _this.noMipmap = noMipmap;
  90964. _this.invertY = invertY;
  90965. _this.samplingMode = samplingMode;
  90966. return _this;
  90967. }
  90968. /**
  90969. * Execute the current task
  90970. * @param scene defines the scene where you want your assets to be loaded
  90971. * @param onSuccess is a callback called when the task is successfully executed
  90972. * @param onError is a callback called if an error occurs
  90973. */
  90974. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90975. var onload = function () {
  90976. onSuccess();
  90977. };
  90978. var onerror = function (message, exception) {
  90979. onError(message, exception);
  90980. };
  90981. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  90982. };
  90983. return TextureAssetTask;
  90984. }(AbstractAssetTask));
  90985. BABYLON.TextureAssetTask = TextureAssetTask;
  90986. /**
  90987. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  90988. */
  90989. var CubeTextureAssetTask = /** @class */ (function (_super) {
  90990. __extends(CubeTextureAssetTask, _super);
  90991. /**
  90992. * Creates a new CubeTextureAssetTask
  90993. * @param name defines the name of the task
  90994. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  90995. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  90996. * @param noMipmap defines if mipmaps should not be generated (default is false)
  90997. * @param files defines the explicit list of files (undefined by default)
  90998. */
  90999. function CubeTextureAssetTask(
  91000. /**
  91001. * Defines the name of the task
  91002. */
  91003. name,
  91004. /**
  91005. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  91006. */
  91007. url,
  91008. /**
  91009. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  91010. */
  91011. extensions,
  91012. /**
  91013. * Defines if mipmaps should not be generated (default is false)
  91014. */
  91015. noMipmap,
  91016. /**
  91017. * Defines the explicit list of files (undefined by default)
  91018. */
  91019. files) {
  91020. var _this = _super.call(this, name) || this;
  91021. _this.name = name;
  91022. _this.url = url;
  91023. _this.extensions = extensions;
  91024. _this.noMipmap = noMipmap;
  91025. _this.files = files;
  91026. return _this;
  91027. }
  91028. /**
  91029. * Execute the current task
  91030. * @param scene defines the scene where you want your assets to be loaded
  91031. * @param onSuccess is a callback called when the task is successfully executed
  91032. * @param onError is a callback called if an error occurs
  91033. */
  91034. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91035. var onload = function () {
  91036. onSuccess();
  91037. };
  91038. var onerror = function (message, exception) {
  91039. onError(message, exception);
  91040. };
  91041. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  91042. };
  91043. return CubeTextureAssetTask;
  91044. }(AbstractAssetTask));
  91045. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  91046. /**
  91047. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  91048. */
  91049. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  91050. __extends(HDRCubeTextureAssetTask, _super);
  91051. /**
  91052. * Creates a new HDRCubeTextureAssetTask object
  91053. * @param name defines the name of the task
  91054. * @param url defines the location of the file to load
  91055. * @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.
  91056. * @param noMipmap defines if mipmaps should not be generated (default is false)
  91057. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  91058. * @param useInGammaSpace 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)
  91059. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  91060. */
  91061. function HDRCubeTextureAssetTask(
  91062. /**
  91063. * Defines the name of the task
  91064. */
  91065. name,
  91066. /**
  91067. * Defines the location of the file to load
  91068. */
  91069. url,
  91070. /**
  91071. * 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.
  91072. */
  91073. size,
  91074. /**
  91075. * Defines if mipmaps should not be generated (default is false)
  91076. */
  91077. noMipmap,
  91078. /**
  91079. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  91080. */
  91081. generateHarmonics,
  91082. /**
  91083. * 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)
  91084. */
  91085. useInGammaSpace,
  91086. /**
  91087. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  91088. */
  91089. usePMREMGenerator) {
  91090. if (noMipmap === void 0) { noMipmap = false; }
  91091. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91092. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  91093. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  91094. var _this = _super.call(this, name) || this;
  91095. _this.name = name;
  91096. _this.url = url;
  91097. _this.size = size;
  91098. _this.noMipmap = noMipmap;
  91099. _this.generateHarmonics = generateHarmonics;
  91100. _this.useInGammaSpace = useInGammaSpace;
  91101. _this.usePMREMGenerator = usePMREMGenerator;
  91102. return _this;
  91103. }
  91104. /**
  91105. * Execute the current task
  91106. * @param scene defines the scene where you want your assets to be loaded
  91107. * @param onSuccess is a callback called when the task is successfully executed
  91108. * @param onError is a callback called if an error occurs
  91109. */
  91110. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  91111. var onload = function () {
  91112. onSuccess();
  91113. };
  91114. var onerror = function (message, exception) {
  91115. onError(message, exception);
  91116. };
  91117. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  91118. };
  91119. return HDRCubeTextureAssetTask;
  91120. }(AbstractAssetTask));
  91121. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  91122. /**
  91123. * This class can be used to easily import assets into a scene
  91124. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  91125. */
  91126. var AssetsManager = /** @class */ (function () {
  91127. /**
  91128. * Creates a new AssetsManager
  91129. * @param scene defines the scene to work on
  91130. */
  91131. function AssetsManager(scene) {
  91132. this._isLoading = false;
  91133. this._tasks = new Array();
  91134. this._waitingTasksCount = 0;
  91135. this._totalTasksCount = 0;
  91136. /**
  91137. * Observable called when all tasks are processed
  91138. */
  91139. this.onTaskSuccessObservable = new BABYLON.Observable();
  91140. /**
  91141. * Observable called when a task had an error
  91142. */
  91143. this.onTaskErrorObservable = new BABYLON.Observable();
  91144. /**
  91145. * Observable called when a task is successful
  91146. */
  91147. this.onTasksDoneObservable = new BABYLON.Observable();
  91148. /**
  91149. * Observable called when a task is done (whatever the result is)
  91150. */
  91151. this.onProgressObservable = new BABYLON.Observable();
  91152. /**
  91153. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  91154. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  91155. */
  91156. this.useDefaultLoadingScreen = true;
  91157. this._scene = scene;
  91158. }
  91159. /**
  91160. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  91161. * @param taskName defines the name of the new task
  91162. * @param meshesNames defines the name of meshes to load
  91163. * @param rootUrl defines the root url to use to locate files
  91164. * @param sceneFilename defines the filename of the scene file
  91165. * @returns a new {BABYLON.MeshAssetTask} object
  91166. */
  91167. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  91168. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  91169. this._tasks.push(task);
  91170. return task;
  91171. };
  91172. /**
  91173. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  91174. * @param taskName defines the name of the new task
  91175. * @param url defines the url of the file to load
  91176. * @returns a new {BABYLON.TextFileAssetTask} object
  91177. */
  91178. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  91179. var task = new TextFileAssetTask(taskName, url);
  91180. this._tasks.push(task);
  91181. return task;
  91182. };
  91183. /**
  91184. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  91185. * @param taskName defines the name of the new task
  91186. * @param url defines the url of the file to load
  91187. * @returns a new {BABYLON.BinaryFileAssetTask} object
  91188. */
  91189. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  91190. var task = new BinaryFileAssetTask(taskName, url);
  91191. this._tasks.push(task);
  91192. return task;
  91193. };
  91194. /**
  91195. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  91196. * @param taskName defines the name of the new task
  91197. * @param url defines the url of the file to load
  91198. * @returns a new {BABYLON.ImageAssetTask} object
  91199. */
  91200. AssetsManager.prototype.addImageTask = function (taskName, url) {
  91201. var task = new ImageAssetTask(taskName, url);
  91202. this._tasks.push(task);
  91203. return task;
  91204. };
  91205. /**
  91206. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  91207. * @param taskName defines the name of the new task
  91208. * @param url defines the url of the file to load
  91209. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91210. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  91211. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  91212. * @returns a new {BABYLON.TextureAssetTask} object
  91213. */
  91214. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  91215. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  91216. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  91217. this._tasks.push(task);
  91218. return task;
  91219. };
  91220. /**
  91221. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  91222. * @param taskName defines the name of the new task
  91223. * @param url defines the url of the file to load
  91224. * @param extensions defines the extension to use to load the cube map (can be null)
  91225. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91226. * @param files defines the list of files to load (can be null)
  91227. * @returns a new {BABYLON.CubeTextureAssetTask} object
  91228. */
  91229. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  91230. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  91231. this._tasks.push(task);
  91232. return task;
  91233. };
  91234. /**
  91235. *
  91236. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  91237. * @param taskName defines the name of the new task
  91238. * @param url defines the url of the file to load
  91239. * @param size defines the size you want for the cubemap (can be null)
  91240. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91241. * @param generateHarmonics defines if you want to automatically generate (true by default)
  91242. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  91243. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  91244. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  91245. */
  91246. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  91247. if (noMipmap === void 0) { noMipmap = false; }
  91248. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91249. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  91250. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  91251. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  91252. this._tasks.push(task);
  91253. return task;
  91254. };
  91255. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  91256. var _this = this;
  91257. this._waitingTasksCount--;
  91258. try {
  91259. if (task.taskState === AssetTaskState.DONE) {
  91260. // Let's remove successfull tasks
  91261. BABYLON.Tools.SetImmediate(function () {
  91262. var index = _this._tasks.indexOf(task);
  91263. if (index > -1) {
  91264. _this._tasks.splice(index, 1);
  91265. }
  91266. });
  91267. }
  91268. if (this.onProgress) {
  91269. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  91270. }
  91271. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  91272. }
  91273. catch (e) {
  91274. BABYLON.Tools.Error("Error running progress callbacks.");
  91275. console.log(e);
  91276. }
  91277. if (this._waitingTasksCount === 0) {
  91278. try {
  91279. if (this.onFinish) {
  91280. this.onFinish(this._tasks);
  91281. }
  91282. this.onTasksDoneObservable.notifyObservers(this._tasks);
  91283. }
  91284. catch (e) {
  91285. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  91286. console.log(e);
  91287. }
  91288. this._isLoading = false;
  91289. this._scene.getEngine().hideLoadingUI();
  91290. }
  91291. };
  91292. AssetsManager.prototype._runTask = function (task) {
  91293. var _this = this;
  91294. var done = function () {
  91295. try {
  91296. if (_this.onTaskSuccess) {
  91297. _this.onTaskSuccess(task);
  91298. }
  91299. _this.onTaskSuccessObservable.notifyObservers(task);
  91300. _this._decreaseWaitingTasksCount(task);
  91301. }
  91302. catch (e) {
  91303. error("Error executing task success callbacks", e);
  91304. }
  91305. };
  91306. var error = function (message, exception) {
  91307. task._setErrorObject(message, exception);
  91308. if (_this.onTaskError) {
  91309. _this.onTaskError(task);
  91310. }
  91311. _this.onTaskErrorObservable.notifyObservers(task);
  91312. _this._decreaseWaitingTasksCount(task);
  91313. };
  91314. task.run(this._scene, done, error);
  91315. };
  91316. /**
  91317. * Reset the {BABYLON.AssetsManager} and remove all tasks
  91318. * @return the current instance of the {BABYLON.AssetsManager}
  91319. */
  91320. AssetsManager.prototype.reset = function () {
  91321. this._isLoading = false;
  91322. this._tasks = new Array();
  91323. return this;
  91324. };
  91325. /**
  91326. * Start the loading process
  91327. * @return the current instance of the {BABYLON.AssetsManager}
  91328. */
  91329. AssetsManager.prototype.load = function () {
  91330. if (this._isLoading) {
  91331. return this;
  91332. }
  91333. this._isLoading = true;
  91334. this._waitingTasksCount = this._tasks.length;
  91335. this._totalTasksCount = this._tasks.length;
  91336. if (this._waitingTasksCount === 0) {
  91337. this._isLoading = false;
  91338. if (this.onFinish) {
  91339. this.onFinish(this._tasks);
  91340. }
  91341. this.onTasksDoneObservable.notifyObservers(this._tasks);
  91342. return this;
  91343. }
  91344. if (this.useDefaultLoadingScreen) {
  91345. this._scene.getEngine().displayLoadingUI();
  91346. }
  91347. for (var index = 0; index < this._tasks.length; index++) {
  91348. var task = this._tasks[index];
  91349. this._runTask(task);
  91350. }
  91351. return this;
  91352. };
  91353. return AssetsManager;
  91354. }());
  91355. BABYLON.AssetsManager = AssetsManager;
  91356. })(BABYLON || (BABYLON = {}));
  91357. //# sourceMappingURL=babylon.assetsManager.js.map
  91358. "use strict";
  91359. var BABYLON;
  91360. (function (BABYLON) {
  91361. var serializedGeometries = [];
  91362. var serializeGeometry = function (geometry, serializationGeometries) {
  91363. if (serializedGeometries[geometry.id]) {
  91364. return;
  91365. }
  91366. if (geometry.doNotSerialize) {
  91367. return;
  91368. }
  91369. if (geometry instanceof BABYLON.BoxGeometry) {
  91370. serializationGeometries.boxes.push(geometry.serialize());
  91371. }
  91372. else if (geometry instanceof BABYLON.SphereGeometry) {
  91373. serializationGeometries.spheres.push(geometry.serialize());
  91374. }
  91375. else if (geometry instanceof BABYLON.CylinderGeometry) {
  91376. serializationGeometries.cylinders.push(geometry.serialize());
  91377. }
  91378. else if (geometry instanceof BABYLON.TorusGeometry) {
  91379. serializationGeometries.toruses.push(geometry.serialize());
  91380. }
  91381. else if (geometry instanceof BABYLON.GroundGeometry) {
  91382. serializationGeometries.grounds.push(geometry.serialize());
  91383. }
  91384. else if (geometry instanceof BABYLON.Plane) {
  91385. serializationGeometries.planes.push(geometry.serialize());
  91386. }
  91387. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  91388. serializationGeometries.torusKnots.push(geometry.serialize());
  91389. }
  91390. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  91391. throw new Error("Unknown primitive type");
  91392. }
  91393. else {
  91394. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  91395. }
  91396. serializedGeometries[geometry.id] = true;
  91397. };
  91398. var serializeMesh = function (mesh, serializationScene) {
  91399. var serializationObject = {};
  91400. // Geometry
  91401. var geometry = mesh._geometry;
  91402. if (geometry) {
  91403. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  91404. // 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
  91405. serializeGeometry(geometry, serializationScene.geometries);
  91406. }
  91407. }
  91408. // Custom
  91409. if (mesh.serialize) {
  91410. mesh.serialize(serializationObject);
  91411. }
  91412. return serializationObject;
  91413. };
  91414. var finalizeSingleMesh = function (mesh, serializationObject) {
  91415. //only works if the mesh is already loaded
  91416. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  91417. //serialize material
  91418. if (mesh.material) {
  91419. if (mesh.material instanceof BABYLON.StandardMaterial) {
  91420. serializationObject.materials = serializationObject.materials || [];
  91421. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  91422. serializationObject.materials.push(mesh.material.serialize());
  91423. }
  91424. }
  91425. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  91426. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  91427. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  91428. serializationObject.multiMaterials.push(mesh.material.serialize());
  91429. }
  91430. }
  91431. }
  91432. //serialize geometry
  91433. var geometry = mesh._geometry;
  91434. if (geometry) {
  91435. if (!serializationObject.geometries) {
  91436. serializationObject.geometries = {};
  91437. serializationObject.geometries.boxes = [];
  91438. serializationObject.geometries.spheres = [];
  91439. serializationObject.geometries.cylinders = [];
  91440. serializationObject.geometries.toruses = [];
  91441. serializationObject.geometries.grounds = [];
  91442. serializationObject.geometries.planes = [];
  91443. serializationObject.geometries.torusKnots = [];
  91444. serializationObject.geometries.vertexData = [];
  91445. }
  91446. serializeGeometry(geometry, serializationObject.geometries);
  91447. }
  91448. // Skeletons
  91449. if (mesh.skeleton) {
  91450. serializationObject.skeletons = serializationObject.skeletons || [];
  91451. serializationObject.skeletons.push(mesh.skeleton.serialize());
  91452. }
  91453. //serialize the actual mesh
  91454. serializationObject.meshes = serializationObject.meshes || [];
  91455. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  91456. }
  91457. };
  91458. var SceneSerializer = /** @class */ (function () {
  91459. function SceneSerializer() {
  91460. }
  91461. SceneSerializer.ClearCache = function () {
  91462. serializedGeometries = [];
  91463. };
  91464. SceneSerializer.Serialize = function (scene) {
  91465. var serializationObject = {};
  91466. SceneSerializer.ClearCache();
  91467. // Scene
  91468. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  91469. serializationObject.autoClear = scene.autoClear;
  91470. serializationObject.clearColor = scene.clearColor.asArray();
  91471. serializationObject.ambientColor = scene.ambientColor.asArray();
  91472. serializationObject.gravity = scene.gravity.asArray();
  91473. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  91474. serializationObject.workerCollisions = scene.workerCollisions;
  91475. // Fog
  91476. if (scene.fogMode && scene.fogMode !== 0) {
  91477. serializationObject.fogMode = scene.fogMode;
  91478. serializationObject.fogColor = scene.fogColor.asArray();
  91479. serializationObject.fogStart = scene.fogStart;
  91480. serializationObject.fogEnd = scene.fogEnd;
  91481. serializationObject.fogDensity = scene.fogDensity;
  91482. }
  91483. //Physics
  91484. if (scene.isPhysicsEnabled()) {
  91485. var physicEngine = scene.getPhysicsEngine();
  91486. if (physicEngine) {
  91487. serializationObject.physicsEnabled = true;
  91488. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  91489. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  91490. }
  91491. }
  91492. // Metadata
  91493. if (scene.metadata) {
  91494. serializationObject.metadata = scene.metadata;
  91495. }
  91496. // Morph targets
  91497. serializationObject.morphTargetManagers = [];
  91498. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  91499. var abstractMesh = _a[_i];
  91500. var manager = abstractMesh.morphTargetManager;
  91501. if (manager) {
  91502. serializationObject.morphTargetManagers.push(manager.serialize());
  91503. }
  91504. }
  91505. // Lights
  91506. serializationObject.lights = [];
  91507. var index;
  91508. var light;
  91509. for (index = 0; index < scene.lights.length; index++) {
  91510. light = scene.lights[index];
  91511. if (!light.doNotSerialize) {
  91512. serializationObject.lights.push(light.serialize());
  91513. }
  91514. }
  91515. // Cameras
  91516. serializationObject.cameras = [];
  91517. for (index = 0; index < scene.cameras.length; index++) {
  91518. var camera = scene.cameras[index];
  91519. if (!camera.doNotSerialize) {
  91520. serializationObject.cameras.push(camera.serialize());
  91521. }
  91522. }
  91523. if (scene.activeCamera) {
  91524. serializationObject.activeCameraID = scene.activeCamera.id;
  91525. }
  91526. // Animations
  91527. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  91528. // Materials
  91529. serializationObject.materials = [];
  91530. serializationObject.multiMaterials = [];
  91531. var material;
  91532. for (index = 0; index < scene.materials.length; index++) {
  91533. material = scene.materials[index];
  91534. if (!material.doNotSerialize) {
  91535. serializationObject.materials.push(material.serialize());
  91536. }
  91537. }
  91538. // MultiMaterials
  91539. serializationObject.multiMaterials = [];
  91540. for (index = 0; index < scene.multiMaterials.length; index++) {
  91541. var multiMaterial = scene.multiMaterials[index];
  91542. serializationObject.multiMaterials.push(multiMaterial.serialize());
  91543. }
  91544. // Environment texture
  91545. if (scene.environmentTexture) {
  91546. serializationObject.environmentTexture = scene.environmentTexture.name;
  91547. }
  91548. // Skeletons
  91549. serializationObject.skeletons = [];
  91550. for (index = 0; index < scene.skeletons.length; index++) {
  91551. var skeleton = scene.skeletons[index];
  91552. if (!skeleton.doNotSerialize) {
  91553. serializationObject.skeletons.push(skeleton.serialize());
  91554. }
  91555. }
  91556. // Transform nodes
  91557. serializationObject.transformNodes = [];
  91558. for (index = 0; index < scene.transformNodes.length; index++) {
  91559. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  91560. }
  91561. // Geometries
  91562. serializationObject.geometries = {};
  91563. serializationObject.geometries.boxes = [];
  91564. serializationObject.geometries.spheres = [];
  91565. serializationObject.geometries.cylinders = [];
  91566. serializationObject.geometries.toruses = [];
  91567. serializationObject.geometries.grounds = [];
  91568. serializationObject.geometries.planes = [];
  91569. serializationObject.geometries.torusKnots = [];
  91570. serializationObject.geometries.vertexData = [];
  91571. serializedGeometries = [];
  91572. var geometries = scene.getGeometries();
  91573. for (index = 0; index < geometries.length; index++) {
  91574. var geometry = geometries[index];
  91575. if (geometry.isReady()) {
  91576. serializeGeometry(geometry, serializationObject.geometries);
  91577. }
  91578. }
  91579. // Meshes
  91580. serializationObject.meshes = [];
  91581. for (index = 0; index < scene.meshes.length; index++) {
  91582. var abstractMesh = scene.meshes[index];
  91583. if (abstractMesh instanceof BABYLON.Mesh) {
  91584. var mesh = abstractMesh;
  91585. if (!mesh.doNotSerialize) {
  91586. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  91587. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  91588. }
  91589. }
  91590. }
  91591. }
  91592. // Particles Systems
  91593. serializationObject.particleSystems = [];
  91594. for (index = 0; index < scene.particleSystems.length; index++) {
  91595. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  91596. }
  91597. // Lens flares
  91598. serializationObject.lensFlareSystems = [];
  91599. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  91600. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  91601. }
  91602. // Shadows
  91603. serializationObject.shadowGenerators = [];
  91604. for (index = 0; index < scene.lights.length; index++) {
  91605. light = scene.lights[index];
  91606. var shadowGenerator = light.getShadowGenerator();
  91607. if (shadowGenerator) {
  91608. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  91609. }
  91610. }
  91611. // Action Manager
  91612. if (scene.actionManager) {
  91613. serializationObject.actions = scene.actionManager.serialize("scene");
  91614. }
  91615. // Audio
  91616. serializationObject.sounds = [];
  91617. for (index = 0; index < scene.soundTracks.length; index++) {
  91618. var soundtrack = scene.soundTracks[index];
  91619. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  91620. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  91621. }
  91622. }
  91623. // Effect layers
  91624. serializationObject.effectLayers = [];
  91625. for (index = 0; index < scene.effectLayers.length; index++) {
  91626. var layer = scene.effectLayers[index];
  91627. if (layer.serialize) {
  91628. serializationObject.effectLayers.push(layer.serialize());
  91629. }
  91630. }
  91631. return serializationObject;
  91632. };
  91633. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  91634. if (withParents === void 0) { withParents = false; }
  91635. if (withChildren === void 0) { withChildren = false; }
  91636. var serializationObject = {};
  91637. SceneSerializer.ClearCache();
  91638. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  91639. if (withParents || withChildren) {
  91640. //deliberate for loop! not for each, appended should be processed as well.
  91641. for (var i = 0; i < toSerialize.length; ++i) {
  91642. if (withChildren) {
  91643. toSerialize[i].getDescendants().forEach(function (node) {
  91644. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  91645. toSerialize.push(node);
  91646. }
  91647. });
  91648. }
  91649. //make sure the array doesn't contain the object already
  91650. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  91651. toSerialize.push(toSerialize[i].parent);
  91652. }
  91653. }
  91654. }
  91655. toSerialize.forEach(function (mesh) {
  91656. finalizeSingleMesh(mesh, serializationObject);
  91657. });
  91658. return serializationObject;
  91659. };
  91660. return SceneSerializer;
  91661. }());
  91662. BABYLON.SceneSerializer = SceneSerializer;
  91663. })(BABYLON || (BABYLON = {}));
  91664. //# sourceMappingURL=babylon.sceneSerializer.js.map
  91665. "use strict";
  91666. var BABYLON;
  91667. (function (BABYLON) {
  91668. var ReflectionProbe = /** @class */ (function () {
  91669. function ReflectionProbe(name, size, scene, generateMipMaps) {
  91670. if (generateMipMaps === void 0) { generateMipMaps = true; }
  91671. var _this = this;
  91672. this.name = name;
  91673. this._viewMatrix = BABYLON.Matrix.Identity();
  91674. this._target = BABYLON.Vector3.Zero();
  91675. this._add = BABYLON.Vector3.Zero();
  91676. this._invertYAxis = false;
  91677. this.position = BABYLON.Vector3.Zero();
  91678. this._scene = scene;
  91679. this._scene.reflectionProbes.push(this);
  91680. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  91681. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  91682. switch (faceIndex) {
  91683. case 0:
  91684. _this._add.copyFromFloats(1, 0, 0);
  91685. break;
  91686. case 1:
  91687. _this._add.copyFromFloats(-1, 0, 0);
  91688. break;
  91689. case 2:
  91690. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  91691. break;
  91692. case 3:
  91693. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  91694. break;
  91695. case 4:
  91696. _this._add.copyFromFloats(0, 0, 1);
  91697. break;
  91698. case 5:
  91699. _this._add.copyFromFloats(0, 0, -1);
  91700. break;
  91701. }
  91702. if (_this._attachedMesh) {
  91703. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  91704. }
  91705. _this.position.addToRef(_this._add, _this._target);
  91706. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  91707. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  91708. scene._forcedViewPosition = _this.position;
  91709. });
  91710. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  91711. scene._forcedViewPosition = null;
  91712. scene.updateTransformMatrix(true);
  91713. });
  91714. if (scene.activeCamera) {
  91715. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  91716. }
  91717. }
  91718. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  91719. get: function () {
  91720. return this._renderTargetTexture.samples;
  91721. },
  91722. set: function (value) {
  91723. this._renderTargetTexture.samples = value;
  91724. },
  91725. enumerable: true,
  91726. configurable: true
  91727. });
  91728. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  91729. get: function () {
  91730. return this._renderTargetTexture.refreshRate;
  91731. },
  91732. set: function (value) {
  91733. this._renderTargetTexture.refreshRate = value;
  91734. },
  91735. enumerable: true,
  91736. configurable: true
  91737. });
  91738. ReflectionProbe.prototype.getScene = function () {
  91739. return this._scene;
  91740. };
  91741. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  91742. get: function () {
  91743. return this._renderTargetTexture;
  91744. },
  91745. enumerable: true,
  91746. configurable: true
  91747. });
  91748. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  91749. get: function () {
  91750. return this._renderTargetTexture.renderList;
  91751. },
  91752. enumerable: true,
  91753. configurable: true
  91754. });
  91755. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  91756. this._attachedMesh = mesh;
  91757. };
  91758. /**
  91759. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  91760. *
  91761. * @param renderingGroupId The rendering group id corresponding to its index
  91762. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  91763. */
  91764. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  91765. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  91766. };
  91767. ReflectionProbe.prototype.dispose = function () {
  91768. var index = this._scene.reflectionProbes.indexOf(this);
  91769. if (index !== -1) {
  91770. // Remove from the scene if found
  91771. this._scene.reflectionProbes.splice(index, 1);
  91772. }
  91773. if (this._renderTargetTexture) {
  91774. this._renderTargetTexture.dispose();
  91775. this._renderTargetTexture = null;
  91776. }
  91777. };
  91778. return ReflectionProbe;
  91779. }());
  91780. BABYLON.ReflectionProbe = ReflectionProbe;
  91781. })(BABYLON || (BABYLON = {}));
  91782. //# sourceMappingURL=babylon.reflectionProbe.js.map
  91783. "use strict";
  91784. var BABYLON;
  91785. (function (BABYLON) {
  91786. var Layer = /** @class */ (function () {
  91787. function Layer(name, imgUrl, scene, isBackground, color) {
  91788. this.name = name;
  91789. this.scale = new BABYLON.Vector2(1, 1);
  91790. this.offset = new BABYLON.Vector2(0, 0);
  91791. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  91792. this.layerMask = 0x0FFFFFFF;
  91793. this._vertexBuffers = {};
  91794. // Events
  91795. /**
  91796. * An event triggered when the layer is disposed.
  91797. */
  91798. this.onDisposeObservable = new BABYLON.Observable();
  91799. /**
  91800. * An event triggered before rendering the scene
  91801. */
  91802. this.onBeforeRenderObservable = new BABYLON.Observable();
  91803. /**
  91804. * An event triggered after rendering the scene
  91805. */
  91806. this.onAfterRenderObservable = new BABYLON.Observable();
  91807. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  91808. this.isBackground = isBackground === undefined ? true : isBackground;
  91809. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  91810. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  91811. this._scene.layers.push(this);
  91812. var engine = this._scene.getEngine();
  91813. // VBO
  91814. var vertices = [];
  91815. vertices.push(1, 1);
  91816. vertices.push(-1, 1);
  91817. vertices.push(-1, -1);
  91818. vertices.push(1, -1);
  91819. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91820. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91821. this._createIndexBuffer();
  91822. // Effects
  91823. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  91824. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  91825. }
  91826. Object.defineProperty(Layer.prototype, "onDispose", {
  91827. set: function (callback) {
  91828. if (this._onDisposeObserver) {
  91829. this.onDisposeObservable.remove(this._onDisposeObserver);
  91830. }
  91831. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  91832. },
  91833. enumerable: true,
  91834. configurable: true
  91835. });
  91836. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  91837. set: function (callback) {
  91838. if (this._onBeforeRenderObserver) {
  91839. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  91840. }
  91841. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  91842. },
  91843. enumerable: true,
  91844. configurable: true
  91845. });
  91846. Object.defineProperty(Layer.prototype, "onAfterRender", {
  91847. set: function (callback) {
  91848. if (this._onAfterRenderObserver) {
  91849. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  91850. }
  91851. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  91852. },
  91853. enumerable: true,
  91854. configurable: true
  91855. });
  91856. Layer.prototype._createIndexBuffer = function () {
  91857. var engine = this._scene.getEngine();
  91858. // Indices
  91859. var indices = [];
  91860. indices.push(0);
  91861. indices.push(1);
  91862. indices.push(2);
  91863. indices.push(0);
  91864. indices.push(2);
  91865. indices.push(3);
  91866. this._indexBuffer = engine.createIndexBuffer(indices);
  91867. };
  91868. Layer.prototype._rebuild = function () {
  91869. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91870. if (vb) {
  91871. vb._rebuild();
  91872. }
  91873. this._createIndexBuffer();
  91874. };
  91875. Layer.prototype.render = function () {
  91876. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  91877. // Check
  91878. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  91879. return;
  91880. var engine = this._scene.getEngine();
  91881. this.onBeforeRenderObservable.notifyObservers(this);
  91882. // Render
  91883. engine.enableEffect(currentEffect);
  91884. engine.setState(false);
  91885. // Texture
  91886. currentEffect.setTexture("textureSampler", this.texture);
  91887. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  91888. // Color
  91889. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  91890. // Scale / offset
  91891. currentEffect.setVector2("offset", this.offset);
  91892. currentEffect.setVector2("scale", this.scale);
  91893. // VBOs
  91894. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91895. // Draw order
  91896. if (!this.alphaTest) {
  91897. engine.setAlphaMode(this.alphaBlendingMode);
  91898. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91899. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  91900. }
  91901. else {
  91902. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91903. }
  91904. this.onAfterRenderObservable.notifyObservers(this);
  91905. };
  91906. Layer.prototype.dispose = function () {
  91907. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91908. if (vertexBuffer) {
  91909. vertexBuffer.dispose();
  91910. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91911. }
  91912. if (this._indexBuffer) {
  91913. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91914. this._indexBuffer = null;
  91915. }
  91916. if (this.texture) {
  91917. this.texture.dispose();
  91918. this.texture = null;
  91919. }
  91920. // Remove from scene
  91921. var index = this._scene.layers.indexOf(this);
  91922. this._scene.layers.splice(index, 1);
  91923. // Callback
  91924. this.onDisposeObservable.notifyObservers(this);
  91925. this.onDisposeObservable.clear();
  91926. this.onAfterRenderObservable.clear();
  91927. this.onBeforeRenderObservable.clear();
  91928. };
  91929. return Layer;
  91930. }());
  91931. BABYLON.Layer = Layer;
  91932. })(BABYLON || (BABYLON = {}));
  91933. //# sourceMappingURL=babylon.layer.js.map
  91934. "use strict";
  91935. var BABYLON;
  91936. (function (BABYLON) {
  91937. var TextureTools = /** @class */ (function () {
  91938. function TextureTools() {
  91939. }
  91940. /**
  91941. * Uses the GPU to create a copy texture rescaled at a given size
  91942. * @param texture Texture to copy from
  91943. * @param width Desired width
  91944. * @param height Desired height
  91945. * @return Generated texture
  91946. */
  91947. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  91948. if (useBilinearMode === void 0) { useBilinearMode = true; }
  91949. var scene = texture.getScene();
  91950. var engine = scene.getEngine();
  91951. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  91952. rtt.wrapU = texture.wrapU;
  91953. rtt.wrapV = texture.wrapV;
  91954. rtt.uOffset = texture.uOffset;
  91955. rtt.vOffset = texture.vOffset;
  91956. rtt.uScale = texture.uScale;
  91957. rtt.vScale = texture.vScale;
  91958. rtt.uAng = texture.uAng;
  91959. rtt.vAng = texture.vAng;
  91960. rtt.wAng = texture.wAng;
  91961. rtt.coordinatesIndex = texture.coordinatesIndex;
  91962. rtt.level = texture.level;
  91963. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  91964. rtt._texture.isReady = false;
  91965. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91966. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91967. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91968. passPostProcess.getEffect().executeWhenCompiled(function () {
  91969. passPostProcess.onApply = function (effect) {
  91970. effect.setTexture("textureSampler", texture);
  91971. };
  91972. var internalTexture = rtt.getInternalTexture();
  91973. if (internalTexture) {
  91974. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  91975. engine.unBindFramebuffer(internalTexture);
  91976. rtt.disposeFramebufferObjects();
  91977. passPostProcess.dispose();
  91978. internalTexture.isReady = true;
  91979. }
  91980. });
  91981. return rtt;
  91982. };
  91983. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  91984. if (!scene._environmentBRDFTexture) {
  91985. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91986. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91987. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91988. scene._environmentBRDFTexture = texture;
  91989. }
  91990. return scene._environmentBRDFTexture;
  91991. };
  91992. 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=";
  91993. return TextureTools;
  91994. }());
  91995. BABYLON.TextureTools = TextureTools;
  91996. })(BABYLON || (BABYLON = {}));
  91997. //# sourceMappingURL=babylon.textureTools.js.map
  91998. "use strict";
  91999. var BABYLON;
  92000. (function (BABYLON) {
  92001. var FramingBehavior = /** @class */ (function () {
  92002. function FramingBehavior() {
  92003. this._mode = FramingBehavior.FitFrustumSidesMode;
  92004. this._radiusScale = 1.0;
  92005. this._positionScale = 0.5;
  92006. this._defaultElevation = 0.3;
  92007. this._elevationReturnTime = 1500;
  92008. this._elevationReturnWaitTime = 1000;
  92009. this._zoomStopsAnimation = false;
  92010. this._framingTime = 1500;
  92011. this._isPointerDown = false;
  92012. this._lastInteractionTime = -Infinity;
  92013. // Framing control
  92014. this._animatables = new Array();
  92015. this._betaIsAnimating = false;
  92016. }
  92017. Object.defineProperty(FramingBehavior.prototype, "name", {
  92018. get: function () {
  92019. return "Framing";
  92020. },
  92021. enumerable: true,
  92022. configurable: true
  92023. });
  92024. Object.defineProperty(FramingBehavior.prototype, "mode", {
  92025. /**
  92026. * Gets current mode used by the behavior.
  92027. */
  92028. get: function () {
  92029. return this._mode;
  92030. },
  92031. /**
  92032. * Sets the current mode used by the behavior
  92033. */
  92034. set: function (mode) {
  92035. this._mode = mode;
  92036. },
  92037. enumerable: true,
  92038. configurable: true
  92039. });
  92040. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  92041. /**
  92042. * Gets the scale applied to the radius
  92043. */
  92044. get: function () {
  92045. return this._radiusScale;
  92046. },
  92047. /**
  92048. * Sets the scale applied to the radius (1 by default)
  92049. */
  92050. set: function (radius) {
  92051. this._radiusScale = radius;
  92052. },
  92053. enumerable: true,
  92054. configurable: true
  92055. });
  92056. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  92057. /**
  92058. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  92059. */
  92060. get: function () {
  92061. return this._positionScale;
  92062. },
  92063. /**
  92064. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  92065. */
  92066. set: function (scale) {
  92067. this._positionScale = scale;
  92068. },
  92069. enumerable: true,
  92070. configurable: true
  92071. });
  92072. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  92073. /**
  92074. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  92075. * behaviour is triggered, in radians.
  92076. */
  92077. get: function () {
  92078. return this._defaultElevation;
  92079. },
  92080. /**
  92081. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  92082. * behaviour is triggered, in radians.
  92083. */
  92084. set: function (elevation) {
  92085. this._defaultElevation = elevation;
  92086. },
  92087. enumerable: true,
  92088. configurable: true
  92089. });
  92090. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  92091. /**
  92092. * Gets the time (in milliseconds) taken to return to the default beta position.
  92093. * Negative value indicates camera should not return to default.
  92094. */
  92095. get: function () {
  92096. return this._elevationReturnTime;
  92097. },
  92098. /**
  92099. * Sets the time (in milliseconds) taken to return to the default beta position.
  92100. * Negative value indicates camera should not return to default.
  92101. */
  92102. set: function (speed) {
  92103. this._elevationReturnTime = speed;
  92104. },
  92105. enumerable: true,
  92106. configurable: true
  92107. });
  92108. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  92109. /**
  92110. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  92111. */
  92112. get: function () {
  92113. return this._elevationReturnWaitTime;
  92114. },
  92115. /**
  92116. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  92117. */
  92118. set: function (time) {
  92119. this._elevationReturnWaitTime = time;
  92120. },
  92121. enumerable: true,
  92122. configurable: true
  92123. });
  92124. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  92125. /**
  92126. * Gets the flag that indicates if user zooming should stop animation.
  92127. */
  92128. get: function () {
  92129. return this._zoomStopsAnimation;
  92130. },
  92131. /**
  92132. * Sets the flag that indicates if user zooming should stop animation.
  92133. */
  92134. set: function (flag) {
  92135. this._zoomStopsAnimation = flag;
  92136. },
  92137. enumerable: true,
  92138. configurable: true
  92139. });
  92140. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  92141. /**
  92142. * Gets the transition time when framing the mesh, in milliseconds
  92143. */
  92144. get: function () {
  92145. return this._framingTime;
  92146. },
  92147. /**
  92148. * Sets the transition time when framing the mesh, in milliseconds
  92149. */
  92150. set: function (time) {
  92151. this._framingTime = time;
  92152. },
  92153. enumerable: true,
  92154. configurable: true
  92155. });
  92156. FramingBehavior.prototype.init = function () {
  92157. // Do notihng
  92158. };
  92159. FramingBehavior.prototype.attach = function (camera) {
  92160. var _this = this;
  92161. this._attachedCamera = camera;
  92162. var scene = this._attachedCamera.getScene();
  92163. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  92164. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  92165. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92166. _this._isPointerDown = true;
  92167. return;
  92168. }
  92169. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  92170. _this._isPointerDown = false;
  92171. }
  92172. });
  92173. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  92174. if (mesh) {
  92175. _this.zoomOnMesh(mesh);
  92176. }
  92177. });
  92178. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92179. // Stop the animation if there is user interaction and the animation should stop for this interaction
  92180. _this._applyUserInteraction();
  92181. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  92182. // back to the default position after a given timeout
  92183. _this._maintainCameraAboveGround();
  92184. });
  92185. };
  92186. FramingBehavior.prototype.detach = function () {
  92187. if (!this._attachedCamera) {
  92188. return;
  92189. }
  92190. var scene = this._attachedCamera.getScene();
  92191. if (this._onPrePointerObservableObserver) {
  92192. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  92193. }
  92194. if (this._onAfterCheckInputsObserver) {
  92195. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92196. }
  92197. if (this._onMeshTargetChangedObserver) {
  92198. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92199. }
  92200. this._attachedCamera = null;
  92201. };
  92202. /**
  92203. * Targets the given mesh and updates zoom level accordingly.
  92204. * @param mesh The mesh to target.
  92205. * @param radius Optional. If a cached radius position already exists, overrides default.
  92206. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92207. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92208. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92209. */
  92210. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  92211. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92212. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92213. mesh.computeWorldMatrix(true);
  92214. var boundingBox = mesh.getBoundingInfo().boundingBox;
  92215. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  92216. };
  92217. /**
  92218. * Targets the given mesh with its children and updates zoom level accordingly.
  92219. * @param mesh The mesh to target.
  92220. * @param radius Optional. If a cached radius position already exists, overrides default.
  92221. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92222. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92223. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92224. */
  92225. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  92226. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92227. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92228. mesh.computeWorldMatrix(true);
  92229. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  92230. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  92231. };
  92232. /**
  92233. * Targets the given meshes with their children and updates zoom level accordingly.
  92234. * @param meshes The mesh to target.
  92235. * @param radius Optional. If a cached radius position already exists, overrides default.
  92236. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92237. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92238. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92239. */
  92240. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  92241. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92242. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92243. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  92244. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  92245. for (var i = 0; i < meshes.length; i++) {
  92246. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  92247. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  92248. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  92249. }
  92250. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  92251. };
  92252. /**
  92253. * Targets the given mesh and updates zoom level accordingly.
  92254. * @param mesh The mesh to target.
  92255. * @param radius Optional. If a cached radius position already exists, overrides default.
  92256. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92257. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92258. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92259. */
  92260. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  92261. var _this = this;
  92262. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92263. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92264. var zoomTarget;
  92265. if (!this._attachedCamera) {
  92266. return;
  92267. }
  92268. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  92269. var bottom = minimumWorld.y;
  92270. var top = maximumWorld.y;
  92271. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  92272. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  92273. if (focusOnOriginXZ) {
  92274. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  92275. }
  92276. else {
  92277. var centerWorld = minimumWorld.add(radiusWorld);
  92278. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  92279. }
  92280. if (!this._vectorTransition) {
  92281. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  92282. }
  92283. this._betaIsAnimating = true;
  92284. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  92285. if (animatable) {
  92286. this._animatables.push(animatable);
  92287. }
  92288. // sets the radius and lower radius bounds
  92289. // Small delta ensures camera is not always at lower zoom limit.
  92290. var radius = 0;
  92291. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  92292. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  92293. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  92294. radius = position;
  92295. }
  92296. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  92297. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  92298. if (this._attachedCamera.lowerRadiusLimit === null) {
  92299. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  92300. }
  92301. }
  92302. // Set sensibilities
  92303. var extend = maximumWorld.subtract(minimumWorld).length();
  92304. this._attachedCamera.panningSensibility = 5000 / extend;
  92305. this._attachedCamera.wheelPrecision = 100 / radius;
  92306. // transition to new radius
  92307. if (!this._radiusTransition) {
  92308. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  92309. }
  92310. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  92311. _this.stopAllAnimations();
  92312. if (onAnimationEnd) {
  92313. onAnimationEnd();
  92314. }
  92315. if (_this._attachedCamera) {
  92316. _this._attachedCamera.storeState();
  92317. }
  92318. });
  92319. if (animatable) {
  92320. this._animatables.push(animatable);
  92321. }
  92322. };
  92323. /**
  92324. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  92325. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  92326. * frustum width.
  92327. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  92328. * to fully enclose the mesh in the viewing frustum.
  92329. */
  92330. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  92331. var size = maximumWorld.subtract(minimumWorld);
  92332. var boxVectorGlobalDiagonal = size.length();
  92333. var frustumSlope = this._getFrustumSlope();
  92334. // Formula for setting distance
  92335. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  92336. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  92337. // Horizon distance
  92338. var radius = radiusWithoutFraming * this._radiusScale;
  92339. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  92340. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  92341. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  92342. var camera = this._attachedCamera;
  92343. if (!camera) {
  92344. return 0;
  92345. }
  92346. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  92347. // Don't exceed the requested limit
  92348. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  92349. }
  92350. // Don't exceed the upper radius limit
  92351. if (camera.upperRadiusLimit) {
  92352. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  92353. }
  92354. return distance;
  92355. };
  92356. /**
  92357. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  92358. * is automatically returned to its default position (expected to be above ground plane).
  92359. */
  92360. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  92361. var _this = this;
  92362. if (this._elevationReturnTime < 0) {
  92363. return;
  92364. }
  92365. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  92366. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  92367. var limitBeta = Math.PI * 0.5;
  92368. // Bring the camera back up if below the ground plane
  92369. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  92370. this._betaIsAnimating = true;
  92371. //Transition to new position
  92372. this.stopAllAnimations();
  92373. if (!this._betaTransition) {
  92374. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  92375. }
  92376. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  92377. _this._clearAnimationLocks();
  92378. _this.stopAllAnimations();
  92379. });
  92380. if (animatabe) {
  92381. this._animatables.push(animatabe);
  92382. }
  92383. }
  92384. };
  92385. /**
  92386. * Returns the frustum slope based on the canvas ratio and camera FOV
  92387. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  92388. */
  92389. FramingBehavior.prototype._getFrustumSlope = function () {
  92390. // Calculate the viewport ratio
  92391. // Aspect Ratio is Height/Width.
  92392. var camera = this._attachedCamera;
  92393. if (!camera) {
  92394. return BABYLON.Vector2.Zero();
  92395. }
  92396. var engine = camera.getScene().getEngine();
  92397. var aspectRatio = engine.getAspectRatio(camera);
  92398. // Camera FOV is the vertical field of view (top-bottom) in radians.
  92399. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  92400. var frustumSlopeY = Math.tan(camera.fov / 2);
  92401. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  92402. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  92403. // along the forward vector.
  92404. var frustumSlopeX = frustumSlopeY * aspectRatio;
  92405. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  92406. };
  92407. /**
  92408. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  92409. */
  92410. FramingBehavior.prototype._clearAnimationLocks = function () {
  92411. this._betaIsAnimating = false;
  92412. };
  92413. /**
  92414. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  92415. */
  92416. FramingBehavior.prototype._applyUserInteraction = function () {
  92417. if (this.isUserIsMoving) {
  92418. this._lastInteractionTime = BABYLON.Tools.Now;
  92419. this.stopAllAnimations();
  92420. this._clearAnimationLocks();
  92421. }
  92422. };
  92423. /**
  92424. * Stops and removes all animations that have been applied to the camera
  92425. */
  92426. FramingBehavior.prototype.stopAllAnimations = function () {
  92427. if (this._attachedCamera) {
  92428. this._attachedCamera.animations = [];
  92429. }
  92430. while (this._animatables.length) {
  92431. if (this._animatables[0]) {
  92432. this._animatables[0].onAnimationEnd = null;
  92433. this._animatables[0].stop();
  92434. }
  92435. this._animatables.shift();
  92436. }
  92437. };
  92438. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  92439. /**
  92440. * Gets a value indicating if the user is moving the camera
  92441. */
  92442. get: function () {
  92443. if (!this._attachedCamera) {
  92444. return false;
  92445. }
  92446. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  92447. this._attachedCamera.inertialBetaOffset !== 0 ||
  92448. this._attachedCamera.inertialRadiusOffset !== 0 ||
  92449. this._attachedCamera.inertialPanningX !== 0 ||
  92450. this._attachedCamera.inertialPanningY !== 0 ||
  92451. this._isPointerDown;
  92452. },
  92453. enumerable: true,
  92454. configurable: true
  92455. });
  92456. /**
  92457. * The easing function used by animations
  92458. */
  92459. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  92460. /**
  92461. * The easing mode used by animations
  92462. */
  92463. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  92464. // Statics
  92465. /**
  92466. * The camera can move all the way towards the mesh.
  92467. */
  92468. FramingBehavior.IgnoreBoundsSizeMode = 0;
  92469. /**
  92470. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  92471. */
  92472. FramingBehavior.FitFrustumSidesMode = 1;
  92473. return FramingBehavior;
  92474. }());
  92475. BABYLON.FramingBehavior = FramingBehavior;
  92476. })(BABYLON || (BABYLON = {}));
  92477. //# sourceMappingURL=babylon.framingBehavior.js.map
  92478. "use strict";
  92479. var BABYLON;
  92480. (function (BABYLON) {
  92481. /**
  92482. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  92483. */
  92484. var BouncingBehavior = /** @class */ (function () {
  92485. function BouncingBehavior() {
  92486. /**
  92487. * The duration of the animation, in milliseconds
  92488. */
  92489. this.transitionDuration = 450;
  92490. /**
  92491. * Length of the distance animated by the transition when lower radius is reached
  92492. */
  92493. this.lowerRadiusTransitionRange = 2;
  92494. /**
  92495. * Length of the distance animated by the transition when upper radius is reached
  92496. */
  92497. this.upperRadiusTransitionRange = -2;
  92498. this._autoTransitionRange = false;
  92499. // Animations
  92500. this._radiusIsAnimating = false;
  92501. this._radiusBounceTransition = null;
  92502. this._animatables = new Array();
  92503. }
  92504. Object.defineProperty(BouncingBehavior.prototype, "name", {
  92505. get: function () {
  92506. return "Bouncing";
  92507. },
  92508. enumerable: true,
  92509. configurable: true
  92510. });
  92511. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  92512. /**
  92513. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  92514. */
  92515. get: function () {
  92516. return this._autoTransitionRange;
  92517. },
  92518. /**
  92519. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  92520. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  92521. */
  92522. set: function (value) {
  92523. var _this = this;
  92524. if (this._autoTransitionRange === value) {
  92525. return;
  92526. }
  92527. this._autoTransitionRange = value;
  92528. var camera = this._attachedCamera;
  92529. if (!camera) {
  92530. return;
  92531. }
  92532. if (value) {
  92533. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  92534. if (!mesh) {
  92535. return;
  92536. }
  92537. mesh.computeWorldMatrix(true);
  92538. var diagonal = mesh.getBoundingInfo().diagonalLength;
  92539. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  92540. _this.upperRadiusTransitionRange = diagonal * 0.05;
  92541. });
  92542. }
  92543. else if (this._onMeshTargetChangedObserver) {
  92544. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92545. }
  92546. },
  92547. enumerable: true,
  92548. configurable: true
  92549. });
  92550. BouncingBehavior.prototype.init = function () {
  92551. // Do notihng
  92552. };
  92553. BouncingBehavior.prototype.attach = function (camera) {
  92554. var _this = this;
  92555. this._attachedCamera = camera;
  92556. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92557. if (!_this._attachedCamera) {
  92558. return;
  92559. }
  92560. // Add the bounce animation to the lower radius limit
  92561. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  92562. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  92563. }
  92564. // Add the bounce animation to the upper radius limit
  92565. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  92566. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  92567. }
  92568. });
  92569. };
  92570. BouncingBehavior.prototype.detach = function () {
  92571. if (!this._attachedCamera) {
  92572. return;
  92573. }
  92574. if (this._onAfterCheckInputsObserver) {
  92575. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92576. }
  92577. if (this._onMeshTargetChangedObserver) {
  92578. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92579. }
  92580. this._attachedCamera = null;
  92581. };
  92582. /**
  92583. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  92584. * @param radiusLimit The limit to check against.
  92585. * @return Bool to indicate if at limit.
  92586. */
  92587. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  92588. if (!this._attachedCamera) {
  92589. return false;
  92590. }
  92591. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  92592. return true;
  92593. }
  92594. return false;
  92595. };
  92596. /**
  92597. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  92598. * @param radiusDelta The delta by which to animate to. Can be negative.
  92599. */
  92600. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  92601. var _this = this;
  92602. if (!this._attachedCamera) {
  92603. return;
  92604. }
  92605. if (!this._radiusBounceTransition) {
  92606. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  92607. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  92608. }
  92609. // Prevent zoom until bounce has completed
  92610. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  92611. this._attachedCamera.wheelPrecision = Infinity;
  92612. this._attachedCamera.inertialRadiusOffset = 0;
  92613. // Animate to the radius limit
  92614. this.stopAllAnimations();
  92615. this._radiusIsAnimating = true;
  92616. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  92617. if (animatable) {
  92618. this._animatables.push(animatable);
  92619. }
  92620. };
  92621. /**
  92622. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  92623. */
  92624. BouncingBehavior.prototype._clearAnimationLocks = function () {
  92625. this._radiusIsAnimating = false;
  92626. if (this._attachedCamera) {
  92627. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  92628. }
  92629. };
  92630. /**
  92631. * Stops and removes all animations that have been applied to the camera
  92632. */
  92633. BouncingBehavior.prototype.stopAllAnimations = function () {
  92634. if (this._attachedCamera) {
  92635. this._attachedCamera.animations = [];
  92636. }
  92637. while (this._animatables.length) {
  92638. this._animatables[0].onAnimationEnd = null;
  92639. this._animatables[0].stop();
  92640. this._animatables.shift();
  92641. }
  92642. };
  92643. /**
  92644. * The easing function used by animations
  92645. */
  92646. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  92647. /**
  92648. * The easing mode used by animations
  92649. */
  92650. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  92651. return BouncingBehavior;
  92652. }());
  92653. BABYLON.BouncingBehavior = BouncingBehavior;
  92654. })(BABYLON || (BABYLON = {}));
  92655. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  92656. "use strict";
  92657. var BABYLON;
  92658. (function (BABYLON) {
  92659. var AutoRotationBehavior = /** @class */ (function () {
  92660. function AutoRotationBehavior() {
  92661. this._zoomStopsAnimation = false;
  92662. this._idleRotationSpeed = 0.05;
  92663. this._idleRotationWaitTime = 2000;
  92664. this._idleRotationSpinupTime = 2000;
  92665. this._isPointerDown = false;
  92666. this._lastFrameTime = null;
  92667. this._lastInteractionTime = -Infinity;
  92668. this._cameraRotationSpeed = 0;
  92669. this._lastFrameRadius = 0;
  92670. }
  92671. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  92672. get: function () {
  92673. return "AutoRotation";
  92674. },
  92675. enumerable: true,
  92676. configurable: true
  92677. });
  92678. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  92679. /**
  92680. * Gets the flag that indicates if user zooming should stop animation.
  92681. */
  92682. get: function () {
  92683. return this._zoomStopsAnimation;
  92684. },
  92685. /**
  92686. * Sets the flag that indicates if user zooming should stop animation.
  92687. */
  92688. set: function (flag) {
  92689. this._zoomStopsAnimation = flag;
  92690. },
  92691. enumerable: true,
  92692. configurable: true
  92693. });
  92694. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  92695. /**
  92696. * Gets the default speed at which the camera rotates around the model.
  92697. */
  92698. get: function () {
  92699. return this._idleRotationSpeed;
  92700. },
  92701. /**
  92702. * Sets the default speed at which the camera rotates around the model.
  92703. */
  92704. set: function (speed) {
  92705. this._idleRotationSpeed = speed;
  92706. },
  92707. enumerable: true,
  92708. configurable: true
  92709. });
  92710. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  92711. /**
  92712. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  92713. */
  92714. get: function () {
  92715. return this._idleRotationWaitTime;
  92716. },
  92717. /**
  92718. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  92719. */
  92720. set: function (time) {
  92721. this._idleRotationWaitTime = time;
  92722. },
  92723. enumerable: true,
  92724. configurable: true
  92725. });
  92726. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  92727. /**
  92728. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  92729. */
  92730. get: function () {
  92731. return this._idleRotationSpinupTime;
  92732. },
  92733. /**
  92734. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  92735. */
  92736. set: function (time) {
  92737. this._idleRotationSpinupTime = time;
  92738. },
  92739. enumerable: true,
  92740. configurable: true
  92741. });
  92742. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  92743. /**
  92744. * Gets a value indicating if the camera is currently rotating because of this behavior
  92745. */
  92746. get: function () {
  92747. return Math.abs(this._cameraRotationSpeed) > 0;
  92748. },
  92749. enumerable: true,
  92750. configurable: true
  92751. });
  92752. AutoRotationBehavior.prototype.init = function () {
  92753. // Do notihng
  92754. };
  92755. AutoRotationBehavior.prototype.attach = function (camera) {
  92756. var _this = this;
  92757. this._attachedCamera = camera;
  92758. var scene = this._attachedCamera.getScene();
  92759. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  92760. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92761. _this._isPointerDown = true;
  92762. return;
  92763. }
  92764. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  92765. _this._isPointerDown = false;
  92766. }
  92767. });
  92768. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92769. var now = BABYLON.Tools.Now;
  92770. var dt = 0;
  92771. if (_this._lastFrameTime != null) {
  92772. dt = now - _this._lastFrameTime;
  92773. }
  92774. _this._lastFrameTime = now;
  92775. // Stop the animation if there is user interaction and the animation should stop for this interaction
  92776. _this._applyUserInteraction();
  92777. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  92778. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  92779. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  92780. // Step camera rotation by rotation speed
  92781. if (_this._attachedCamera) {
  92782. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  92783. }
  92784. });
  92785. };
  92786. AutoRotationBehavior.prototype.detach = function () {
  92787. if (!this._attachedCamera) {
  92788. return;
  92789. }
  92790. var scene = this._attachedCamera.getScene();
  92791. if (this._onPrePointerObservableObserver) {
  92792. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  92793. }
  92794. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92795. this._attachedCamera = null;
  92796. };
  92797. /**
  92798. * Returns true if user is scrolling.
  92799. * @return true if user is scrolling.
  92800. */
  92801. AutoRotationBehavior.prototype._userIsZooming = function () {
  92802. if (!this._attachedCamera) {
  92803. return false;
  92804. }
  92805. return this._attachedCamera.inertialRadiusOffset !== 0;
  92806. };
  92807. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  92808. if (!this._attachedCamera) {
  92809. return false;
  92810. }
  92811. var zoomHasHitLimit = false;
  92812. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  92813. zoomHasHitLimit = true;
  92814. }
  92815. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  92816. this._lastFrameRadius = this._attachedCamera.radius;
  92817. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  92818. };
  92819. /**
  92820. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  92821. */
  92822. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  92823. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  92824. this._lastInteractionTime = BABYLON.Tools.Now;
  92825. }
  92826. };
  92827. // Tools
  92828. AutoRotationBehavior.prototype._userIsMoving = function () {
  92829. if (!this._attachedCamera) {
  92830. return false;
  92831. }
  92832. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  92833. this._attachedCamera.inertialBetaOffset !== 0 ||
  92834. this._attachedCamera.inertialRadiusOffset !== 0 ||
  92835. this._attachedCamera.inertialPanningX !== 0 ||
  92836. this._attachedCamera.inertialPanningY !== 0 ||
  92837. this._isPointerDown;
  92838. };
  92839. return AutoRotationBehavior;
  92840. }());
  92841. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  92842. })(BABYLON || (BABYLON = {}));
  92843. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  92844. "use strict";
  92845. var BABYLON;
  92846. (function (BABYLON) {
  92847. var NullEngineOptions = /** @class */ (function () {
  92848. function NullEngineOptions() {
  92849. this.renderWidth = 512;
  92850. this.renderHeight = 256;
  92851. this.textureSize = 512;
  92852. this.deterministicLockstep = false;
  92853. this.lockstepMaxSteps = 4;
  92854. }
  92855. return NullEngineOptions;
  92856. }());
  92857. BABYLON.NullEngineOptions = NullEngineOptions;
  92858. /**
  92859. * The null engine class provides support for headless version of babylon.js.
  92860. * This can be used in server side scenario or for testing purposes
  92861. */
  92862. var NullEngine = /** @class */ (function (_super) {
  92863. __extends(NullEngine, _super);
  92864. function NullEngine(options) {
  92865. if (options === void 0) { options = new NullEngineOptions(); }
  92866. var _this = _super.call(this, null) || this;
  92867. if (options.deterministicLockstep === undefined) {
  92868. options.deterministicLockstep = false;
  92869. }
  92870. if (options.lockstepMaxSteps === undefined) {
  92871. options.lockstepMaxSteps = 4;
  92872. }
  92873. _this._options = options;
  92874. // Init caps
  92875. // We consider we are on a webgl1 capable device
  92876. _this._caps = new BABYLON.EngineCapabilities();
  92877. _this._caps.maxTexturesImageUnits = 16;
  92878. _this._caps.maxVertexTextureImageUnits = 16;
  92879. _this._caps.maxTextureSize = 512;
  92880. _this._caps.maxCubemapTextureSize = 512;
  92881. _this._caps.maxRenderTextureSize = 512;
  92882. _this._caps.maxVertexAttribs = 16;
  92883. _this._caps.maxVaryingVectors = 16;
  92884. _this._caps.maxFragmentUniformVectors = 16;
  92885. _this._caps.maxVertexUniformVectors = 16;
  92886. // Extensions
  92887. _this._caps.standardDerivatives = false;
  92888. _this._caps.astc = null;
  92889. _this._caps.s3tc = null;
  92890. _this._caps.pvrtc = null;
  92891. _this._caps.etc1 = null;
  92892. _this._caps.etc2 = null;
  92893. _this._caps.textureAnisotropicFilterExtension = null;
  92894. _this._caps.maxAnisotropy = 0;
  92895. _this._caps.uintIndices = false;
  92896. _this._caps.fragmentDepthSupported = false;
  92897. _this._caps.highPrecisionShaderSupported = true;
  92898. _this._caps.colorBufferFloat = false;
  92899. _this._caps.textureFloat = false;
  92900. _this._caps.textureFloatLinearFiltering = false;
  92901. _this._caps.textureFloatRender = false;
  92902. _this._caps.textureHalfFloat = false;
  92903. _this._caps.textureHalfFloatLinearFiltering = false;
  92904. _this._caps.textureHalfFloatRender = false;
  92905. _this._caps.textureLOD = false;
  92906. _this._caps.drawBuffersExtension = false;
  92907. _this._caps.depthTextureExtension = false;
  92908. _this._caps.vertexArrayObject = false;
  92909. _this._caps.instancedArrays = false;
  92910. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  92911. // Wrappers
  92912. if (typeof URL === "undefined") {
  92913. URL = {
  92914. createObjectURL: function () { },
  92915. revokeObjectURL: function () { }
  92916. };
  92917. }
  92918. if (typeof Blob === "undefined") {
  92919. Blob = function () { };
  92920. }
  92921. return _this;
  92922. }
  92923. NullEngine.prototype.isDeterministicLockStep = function () {
  92924. return this._options.deterministicLockstep;
  92925. };
  92926. NullEngine.prototype.getLockstepMaxSteps = function () {
  92927. return this._options.lockstepMaxSteps;
  92928. };
  92929. NullEngine.prototype.getHardwareScalingLevel = function () {
  92930. return 1.0;
  92931. };
  92932. NullEngine.prototype.createVertexBuffer = function (vertices) {
  92933. return {
  92934. capacity: 0,
  92935. references: 1,
  92936. is32Bits: false
  92937. };
  92938. };
  92939. NullEngine.prototype.createIndexBuffer = function (indices) {
  92940. return {
  92941. capacity: 0,
  92942. references: 1,
  92943. is32Bits: false
  92944. };
  92945. };
  92946. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  92947. if (stencil === void 0) { stencil = false; }
  92948. };
  92949. NullEngine.prototype.getRenderWidth = function (useScreen) {
  92950. if (useScreen === void 0) { useScreen = false; }
  92951. if (!useScreen && this._currentRenderTarget) {
  92952. return this._currentRenderTarget.width;
  92953. }
  92954. return this._options.renderWidth;
  92955. };
  92956. NullEngine.prototype.getRenderHeight = function (useScreen) {
  92957. if (useScreen === void 0) { useScreen = false; }
  92958. if (!useScreen && this._currentRenderTarget) {
  92959. return this._currentRenderTarget.height;
  92960. }
  92961. return this._options.renderHeight;
  92962. };
  92963. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  92964. this._cachedViewport = viewport;
  92965. };
  92966. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  92967. return {
  92968. transformFeedback: null,
  92969. __SPECTOR_rebuildProgram: null
  92970. };
  92971. };
  92972. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  92973. return [];
  92974. };
  92975. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  92976. return [];
  92977. };
  92978. NullEngine.prototype.bindSamplers = function (effect) {
  92979. this._currentEffect = null;
  92980. };
  92981. NullEngine.prototype.enableEffect = function (effect) {
  92982. this._currentEffect = effect;
  92983. if (effect.onBind) {
  92984. effect.onBind(effect);
  92985. }
  92986. effect.onBindObservable.notifyObservers(effect);
  92987. };
  92988. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  92989. if (zOffset === void 0) { zOffset = 0; }
  92990. if (reverseSide === void 0) { reverseSide = false; }
  92991. };
  92992. NullEngine.prototype.setIntArray = function (uniform, array) {
  92993. };
  92994. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  92995. };
  92996. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  92997. };
  92998. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  92999. };
  93000. NullEngine.prototype.setFloatArray = function (uniform, array) {
  93001. };
  93002. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  93003. };
  93004. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  93005. };
  93006. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  93007. };
  93008. NullEngine.prototype.setArray = function (uniform, array) {
  93009. };
  93010. NullEngine.prototype.setArray2 = function (uniform, array) {
  93011. };
  93012. NullEngine.prototype.setArray3 = function (uniform, array) {
  93013. };
  93014. NullEngine.prototype.setArray4 = function (uniform, array) {
  93015. };
  93016. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  93017. };
  93018. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  93019. };
  93020. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  93021. };
  93022. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  93023. };
  93024. NullEngine.prototype.setFloat = function (uniform, value) {
  93025. };
  93026. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  93027. };
  93028. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  93029. };
  93030. NullEngine.prototype.setBool = function (uniform, bool) {
  93031. };
  93032. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  93033. };
  93034. NullEngine.prototype.setColor3 = function (uniform, color3) {
  93035. };
  93036. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  93037. };
  93038. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  93039. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  93040. if (this._alphaMode === mode) {
  93041. return;
  93042. }
  93043. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  93044. if (!noDepthWriteChange) {
  93045. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  93046. }
  93047. this._alphaMode = mode;
  93048. };
  93049. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  93050. };
  93051. NullEngine.prototype.wipeCaches = function (bruteForce) {
  93052. if (this.preventCacheWipeBetweenFrames) {
  93053. return;
  93054. }
  93055. this.resetTextureCache();
  93056. this._currentEffect = null;
  93057. if (bruteForce) {
  93058. this._currentProgram = null;
  93059. this._stencilState.reset();
  93060. this._depthCullingState.reset();
  93061. this._alphaState.reset();
  93062. }
  93063. this._cachedVertexBuffers = null;
  93064. this._cachedIndexBuffer = null;
  93065. this._cachedEffectForVertexBuffers = null;
  93066. };
  93067. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  93068. };
  93069. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  93070. };
  93071. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  93072. };
  93073. NullEngine.prototype._createTexture = function () {
  93074. return {};
  93075. };
  93076. NullEngine.prototype._releaseTexture = function (texture) {
  93077. };
  93078. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  93079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93080. if (onLoad === void 0) { onLoad = null; }
  93081. if (onError === void 0) { onError = null; }
  93082. if (buffer === void 0) { buffer = null; }
  93083. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  93084. var url = String(urlArg);
  93085. texture.url = url;
  93086. texture.generateMipMaps = !noMipmap;
  93087. texture.samplingMode = samplingMode;
  93088. texture.invertY = invertY;
  93089. texture.baseWidth = this._options.textureSize;
  93090. texture.baseHeight = this._options.textureSize;
  93091. texture.width = this._options.textureSize;
  93092. texture.height = this._options.textureSize;
  93093. if (format) {
  93094. texture.format = format;
  93095. }
  93096. texture.isReady = true;
  93097. if (onLoad) {
  93098. onLoad();
  93099. }
  93100. return texture;
  93101. };
  93102. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  93103. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  93104. if (options !== undefined && typeof options === "object") {
  93105. fullOptions.generateMipMaps = options.generateMipMaps;
  93106. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  93107. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  93108. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  93109. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  93110. }
  93111. else {
  93112. fullOptions.generateMipMaps = options;
  93113. fullOptions.generateDepthBuffer = true;
  93114. fullOptions.generateStencilBuffer = false;
  93115. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93116. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  93117. }
  93118. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  93119. var width = size.width || size;
  93120. var height = size.height || size;
  93121. texture._depthStencilBuffer = {};
  93122. texture._framebuffer = {};
  93123. texture.baseWidth = width;
  93124. texture.baseHeight = height;
  93125. texture.width = width;
  93126. texture.height = height;
  93127. texture.isReady = true;
  93128. texture.samples = 1;
  93129. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  93130. texture.samplingMode = fullOptions.samplingMode;
  93131. texture.type = fullOptions.type;
  93132. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  93133. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  93134. return texture;
  93135. };
  93136. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  93137. texture.samplingMode = samplingMode;
  93138. };
  93139. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  93140. if (this._currentRenderTarget) {
  93141. this.unBindFramebuffer(this._currentRenderTarget);
  93142. }
  93143. this._currentRenderTarget = texture;
  93144. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  93145. if (this._cachedViewport && !forceFullscreenViewport) {
  93146. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  93147. }
  93148. };
  93149. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  93150. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  93151. this._currentRenderTarget = null;
  93152. if (onBeforeUnbind) {
  93153. if (texture._MSAAFramebuffer) {
  93154. this._currentFramebuffer = texture._framebuffer;
  93155. }
  93156. onBeforeUnbind();
  93157. }
  93158. this._currentFramebuffer = null;
  93159. };
  93160. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  93161. var vbo = {
  93162. capacity: 1,
  93163. references: 1,
  93164. is32Bits: false
  93165. };
  93166. return vbo;
  93167. };
  93168. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  93169. if (offset === void 0) { offset = 0; }
  93170. };
  93171. /**
  93172. * Updates a dynamic vertex buffer.
  93173. * @param vertexBuffer the vertex buffer to update
  93174. * @param data the data used to update the vertex buffer
  93175. * @param byteOffset the byte offset of the data (optional)
  93176. * @param byteLength the byte length of the data (optional)
  93177. */
  93178. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  93179. };
  93180. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  93181. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  93182. this._boundTexturesCache[this._activeChannel] = texture;
  93183. }
  93184. };
  93185. NullEngine.prototype._bindTexture = function (channel, texture) {
  93186. if (channel < 0) {
  93187. return;
  93188. }
  93189. this._bindTextureDirectly(0, texture);
  93190. };
  93191. NullEngine.prototype._releaseBuffer = function (buffer) {
  93192. buffer.references--;
  93193. if (buffer.references === 0) {
  93194. return true;
  93195. }
  93196. return false;
  93197. };
  93198. return NullEngine;
  93199. }(BABYLON.Engine));
  93200. BABYLON.NullEngine = NullEngine;
  93201. })(BABYLON || (BABYLON = {}));
  93202. //# sourceMappingURL=babylon.nullEngine.js.map
  93203. "use strict";
  93204. var BABYLON;
  93205. (function (BABYLON) {
  93206. /**
  93207. * This class can be used to get instrumentation data from a Babylon engine
  93208. */
  93209. var EngineInstrumentation = /** @class */ (function () {
  93210. function EngineInstrumentation(engine) {
  93211. this.engine = engine;
  93212. this._captureGPUFrameTime = false;
  93213. this._gpuFrameTime = new BABYLON.PerfCounter();
  93214. this._captureShaderCompilationTime = false;
  93215. this._shaderCompilationTime = new BABYLON.PerfCounter();
  93216. // Observers
  93217. this._onBeginFrameObserver = null;
  93218. this._onEndFrameObserver = null;
  93219. this._onBeforeShaderCompilationObserver = null;
  93220. this._onAfterShaderCompilationObserver = null;
  93221. }
  93222. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  93223. // Properties
  93224. /**
  93225. * Gets the perf counter used for GPU frame time
  93226. */
  93227. get: function () {
  93228. return this._gpuFrameTime;
  93229. },
  93230. enumerable: true,
  93231. configurable: true
  93232. });
  93233. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  93234. /**
  93235. * Gets the GPU frame time capture status
  93236. */
  93237. get: function () {
  93238. return this._captureGPUFrameTime;
  93239. },
  93240. /**
  93241. * Enable or disable the GPU frame time capture
  93242. */
  93243. set: function (value) {
  93244. var _this = this;
  93245. if (value === this._captureGPUFrameTime) {
  93246. return;
  93247. }
  93248. this._captureGPUFrameTime = value;
  93249. if (value) {
  93250. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  93251. if (!_this._gpuFrameTimeToken) {
  93252. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  93253. }
  93254. });
  93255. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  93256. if (!_this._gpuFrameTimeToken) {
  93257. return;
  93258. }
  93259. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  93260. if (time > -1) {
  93261. _this._gpuFrameTimeToken = null;
  93262. _this._gpuFrameTime.fetchNewFrame();
  93263. _this._gpuFrameTime.addCount(time, true);
  93264. }
  93265. });
  93266. }
  93267. else {
  93268. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  93269. this._onBeginFrameObserver = null;
  93270. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  93271. this._onEndFrameObserver = null;
  93272. }
  93273. },
  93274. enumerable: true,
  93275. configurable: true
  93276. });
  93277. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  93278. /**
  93279. * Gets the perf counter used for shader compilation time
  93280. */
  93281. get: function () {
  93282. return this._shaderCompilationTime;
  93283. },
  93284. enumerable: true,
  93285. configurable: true
  93286. });
  93287. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  93288. /**
  93289. * Gets the shader compilation time capture status
  93290. */
  93291. get: function () {
  93292. return this._captureShaderCompilationTime;
  93293. },
  93294. /**
  93295. * Enable or disable the shader compilation time capture
  93296. */
  93297. set: function (value) {
  93298. var _this = this;
  93299. if (value === this._captureShaderCompilationTime) {
  93300. return;
  93301. }
  93302. this._captureShaderCompilationTime = value;
  93303. if (value) {
  93304. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  93305. _this._shaderCompilationTime.fetchNewFrame();
  93306. _this._shaderCompilationTime.beginMonitoring();
  93307. });
  93308. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  93309. _this._shaderCompilationTime.endMonitoring();
  93310. });
  93311. }
  93312. else {
  93313. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  93314. this._onBeforeShaderCompilationObserver = null;
  93315. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  93316. this._onAfterShaderCompilationObserver = null;
  93317. }
  93318. },
  93319. enumerable: true,
  93320. configurable: true
  93321. });
  93322. EngineInstrumentation.prototype.dispose = function () {
  93323. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  93324. this._onBeginFrameObserver = null;
  93325. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  93326. this._onEndFrameObserver = null;
  93327. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  93328. this._onBeforeShaderCompilationObserver = null;
  93329. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  93330. this._onAfterShaderCompilationObserver = null;
  93331. this.engine = null;
  93332. };
  93333. return EngineInstrumentation;
  93334. }());
  93335. BABYLON.EngineInstrumentation = EngineInstrumentation;
  93336. })(BABYLON || (BABYLON = {}));
  93337. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  93338. "use strict";
  93339. var BABYLON;
  93340. (function (BABYLON) {
  93341. /**
  93342. * This class can be used to get instrumentation data from a Babylon engine
  93343. */
  93344. var SceneInstrumentation = /** @class */ (function () {
  93345. function SceneInstrumentation(scene) {
  93346. var _this = this;
  93347. this.scene = scene;
  93348. this._captureActiveMeshesEvaluationTime = false;
  93349. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  93350. this._captureRenderTargetsRenderTime = false;
  93351. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  93352. this._captureFrameTime = false;
  93353. this._frameTime = new BABYLON.PerfCounter();
  93354. this._captureRenderTime = false;
  93355. this._renderTime = new BABYLON.PerfCounter();
  93356. this._captureInterFrameTime = false;
  93357. this._interFrameTime = new BABYLON.PerfCounter();
  93358. this._captureParticlesRenderTime = false;
  93359. this._particlesRenderTime = new BABYLON.PerfCounter();
  93360. this._captureSpritesRenderTime = false;
  93361. this._spritesRenderTime = new BABYLON.PerfCounter();
  93362. this._capturePhysicsTime = false;
  93363. this._physicsTime = new BABYLON.PerfCounter();
  93364. this._captureAnimationsTime = false;
  93365. this._animationsTime = new BABYLON.PerfCounter();
  93366. // Observers
  93367. this._onBeforeActiveMeshesEvaluationObserver = null;
  93368. this._onAfterActiveMeshesEvaluationObserver = null;
  93369. this._onBeforeRenderTargetsRenderObserver = null;
  93370. this._onAfterRenderTargetsRenderObserver = null;
  93371. this._onAfterRenderObserver = null;
  93372. this._onBeforeDrawPhaseObserver = null;
  93373. this._onAfterDrawPhaseObserver = null;
  93374. this._onBeforeAnimationsObserver = null;
  93375. this._onBeforeParticlesRenderingObserver = null;
  93376. this._onAfterParticlesRenderingObserver = null;
  93377. this._onBeforeSpritesRenderingObserver = null;
  93378. this._onAfterSpritesRenderingObserver = null;
  93379. this._onBeforePhysicsObserver = null;
  93380. this._onAfterPhysicsObserver = null;
  93381. this._onAfterAnimationsObserver = null;
  93382. // Before render
  93383. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  93384. if (_this._captureActiveMeshesEvaluationTime) {
  93385. _this._activeMeshesEvaluationTime.fetchNewFrame();
  93386. }
  93387. if (_this._captureRenderTargetsRenderTime) {
  93388. _this._renderTargetsRenderTime.fetchNewFrame();
  93389. }
  93390. if (_this._captureFrameTime) {
  93391. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  93392. _this._frameTime.beginMonitoring();
  93393. }
  93394. if (_this._captureInterFrameTime) {
  93395. _this._interFrameTime.endMonitoring();
  93396. }
  93397. if (_this._captureParticlesRenderTime) {
  93398. _this._particlesRenderTime.fetchNewFrame();
  93399. }
  93400. if (_this._captureSpritesRenderTime) {
  93401. _this._spritesRenderTime.fetchNewFrame();
  93402. }
  93403. if (_this._captureAnimationsTime) {
  93404. _this._animationsTime.beginMonitoring();
  93405. }
  93406. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  93407. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  93408. });
  93409. // After render
  93410. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  93411. if (_this._captureFrameTime) {
  93412. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  93413. _this._frameTime.endMonitoring();
  93414. }
  93415. if (_this._captureRenderTime) {
  93416. _this._renderTime.endMonitoring(false);
  93417. }
  93418. if (_this._captureInterFrameTime) {
  93419. _this._interFrameTime.beginMonitoring();
  93420. }
  93421. });
  93422. }
  93423. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  93424. // Properties
  93425. /**
  93426. * Gets the perf counter used for active meshes evaluation time
  93427. */
  93428. get: function () {
  93429. return this._activeMeshesEvaluationTime;
  93430. },
  93431. enumerable: true,
  93432. configurable: true
  93433. });
  93434. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  93435. /**
  93436. * Gets the active meshes evaluation time capture status
  93437. */
  93438. get: function () {
  93439. return this._captureActiveMeshesEvaluationTime;
  93440. },
  93441. /**
  93442. * Enable or disable the active meshes evaluation time capture
  93443. */
  93444. set: function (value) {
  93445. var _this = this;
  93446. if (value === this._captureActiveMeshesEvaluationTime) {
  93447. return;
  93448. }
  93449. this._captureActiveMeshesEvaluationTime = value;
  93450. if (value) {
  93451. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  93452. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  93453. _this._activeMeshesEvaluationTime.beginMonitoring();
  93454. });
  93455. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  93456. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  93457. _this._activeMeshesEvaluationTime.endMonitoring();
  93458. });
  93459. }
  93460. else {
  93461. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  93462. this._onBeforeActiveMeshesEvaluationObserver = null;
  93463. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  93464. this._onAfterActiveMeshesEvaluationObserver = null;
  93465. }
  93466. },
  93467. enumerable: true,
  93468. configurable: true
  93469. });
  93470. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  93471. /**
  93472. * Gets the perf counter used for render targets render time
  93473. */
  93474. get: function () {
  93475. return this._renderTargetsRenderTime;
  93476. },
  93477. enumerable: true,
  93478. configurable: true
  93479. });
  93480. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  93481. /**
  93482. * Gets the render targets render time capture status
  93483. */
  93484. get: function () {
  93485. return this._captureRenderTargetsRenderTime;
  93486. },
  93487. /**
  93488. * Enable or disable the render targets render time capture
  93489. */
  93490. set: function (value) {
  93491. var _this = this;
  93492. if (value === this._captureRenderTargetsRenderTime) {
  93493. return;
  93494. }
  93495. this._captureRenderTargetsRenderTime = value;
  93496. if (value) {
  93497. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  93498. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  93499. _this._renderTargetsRenderTime.beginMonitoring();
  93500. });
  93501. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  93502. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  93503. _this._renderTargetsRenderTime.endMonitoring(false);
  93504. });
  93505. }
  93506. else {
  93507. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  93508. this._onBeforeRenderTargetsRenderObserver = null;
  93509. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  93510. this._onAfterRenderTargetsRenderObserver = null;
  93511. }
  93512. },
  93513. enumerable: true,
  93514. configurable: true
  93515. });
  93516. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  93517. /**
  93518. * Gets the perf counter used for particles render time
  93519. */
  93520. get: function () {
  93521. return this._particlesRenderTime;
  93522. },
  93523. enumerable: true,
  93524. configurable: true
  93525. });
  93526. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  93527. /**
  93528. * Gets the particles render time capture status
  93529. */
  93530. get: function () {
  93531. return this._captureParticlesRenderTime;
  93532. },
  93533. /**
  93534. * Enable or disable the particles render time capture
  93535. */
  93536. set: function (value) {
  93537. var _this = this;
  93538. if (value === this._captureParticlesRenderTime) {
  93539. return;
  93540. }
  93541. this._captureParticlesRenderTime = value;
  93542. if (value) {
  93543. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  93544. BABYLON.Tools.StartPerformanceCounter("Particles");
  93545. _this._particlesRenderTime.beginMonitoring();
  93546. });
  93547. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  93548. BABYLON.Tools.EndPerformanceCounter("Particles");
  93549. _this._particlesRenderTime.endMonitoring(false);
  93550. });
  93551. }
  93552. else {
  93553. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  93554. this._onBeforeParticlesRenderingObserver = null;
  93555. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  93556. this._onAfterParticlesRenderingObserver = null;
  93557. }
  93558. },
  93559. enumerable: true,
  93560. configurable: true
  93561. });
  93562. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  93563. /**
  93564. * Gets the perf counter used for sprites render time
  93565. */
  93566. get: function () {
  93567. return this._spritesRenderTime;
  93568. },
  93569. enumerable: true,
  93570. configurable: true
  93571. });
  93572. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  93573. /**
  93574. * Gets the sprites render time capture status
  93575. */
  93576. get: function () {
  93577. return this._captureSpritesRenderTime;
  93578. },
  93579. /**
  93580. * Enable or disable the sprites render time capture
  93581. */
  93582. set: function (value) {
  93583. var _this = this;
  93584. if (value === this._captureSpritesRenderTime) {
  93585. return;
  93586. }
  93587. this._captureSpritesRenderTime = value;
  93588. if (value) {
  93589. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  93590. BABYLON.Tools.StartPerformanceCounter("Sprites");
  93591. _this._spritesRenderTime.beginMonitoring();
  93592. });
  93593. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  93594. BABYLON.Tools.EndPerformanceCounter("Sprites");
  93595. _this._spritesRenderTime.endMonitoring(false);
  93596. });
  93597. }
  93598. else {
  93599. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  93600. this._onBeforeSpritesRenderingObserver = null;
  93601. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  93602. this._onAfterSpritesRenderingObserver = null;
  93603. }
  93604. },
  93605. enumerable: true,
  93606. configurable: true
  93607. });
  93608. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  93609. /**
  93610. * Gets the perf counter used for physics time
  93611. */
  93612. get: function () {
  93613. return this._physicsTime;
  93614. },
  93615. enumerable: true,
  93616. configurable: true
  93617. });
  93618. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  93619. /**
  93620. * Gets the physics time capture status
  93621. */
  93622. get: function () {
  93623. return this._capturePhysicsTime;
  93624. },
  93625. /**
  93626. * Enable or disable the physics time capture
  93627. */
  93628. set: function (value) {
  93629. var _this = this;
  93630. if (value === this._capturePhysicsTime) {
  93631. return;
  93632. }
  93633. this._capturePhysicsTime = value;
  93634. if (value) {
  93635. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  93636. BABYLON.Tools.StartPerformanceCounter("Physics");
  93637. _this._physicsTime.beginMonitoring();
  93638. });
  93639. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  93640. BABYLON.Tools.EndPerformanceCounter("Physics");
  93641. _this._physicsTime.endMonitoring();
  93642. });
  93643. }
  93644. else {
  93645. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  93646. this._onBeforePhysicsObserver = null;
  93647. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  93648. this._onAfterPhysicsObserver = null;
  93649. }
  93650. },
  93651. enumerable: true,
  93652. configurable: true
  93653. });
  93654. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  93655. /**
  93656. * Gets the perf counter used for animations time
  93657. */
  93658. get: function () {
  93659. return this._animationsTime;
  93660. },
  93661. enumerable: true,
  93662. configurable: true
  93663. });
  93664. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  93665. /**
  93666. * Gets the animations time capture status
  93667. */
  93668. get: function () {
  93669. return this._captureAnimationsTime;
  93670. },
  93671. /**
  93672. * Enable or disable the animations time capture
  93673. */
  93674. set: function (value) {
  93675. var _this = this;
  93676. if (value === this._captureAnimationsTime) {
  93677. return;
  93678. }
  93679. this._captureAnimationsTime = value;
  93680. if (value) {
  93681. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  93682. _this._animationsTime.endMonitoring();
  93683. });
  93684. }
  93685. else {
  93686. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  93687. this._onAfterAnimationsObserver = null;
  93688. }
  93689. },
  93690. enumerable: true,
  93691. configurable: true
  93692. });
  93693. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  93694. /**
  93695. * Gets the perf counter used for frame time capture
  93696. */
  93697. get: function () {
  93698. return this._frameTime;
  93699. },
  93700. enumerable: true,
  93701. configurable: true
  93702. });
  93703. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  93704. /**
  93705. * Gets the frame time capture status
  93706. */
  93707. get: function () {
  93708. return this._captureFrameTime;
  93709. },
  93710. /**
  93711. * Enable or disable the frame time capture
  93712. */
  93713. set: function (value) {
  93714. this._captureFrameTime = value;
  93715. },
  93716. enumerable: true,
  93717. configurable: true
  93718. });
  93719. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  93720. /**
  93721. * Gets the perf counter used for inter-frames time capture
  93722. */
  93723. get: function () {
  93724. return this._interFrameTime;
  93725. },
  93726. enumerable: true,
  93727. configurable: true
  93728. });
  93729. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  93730. /**
  93731. * Gets the inter-frames time capture status
  93732. */
  93733. get: function () {
  93734. return this._captureInterFrameTime;
  93735. },
  93736. /**
  93737. * Enable or disable the inter-frames time capture
  93738. */
  93739. set: function (value) {
  93740. this._captureInterFrameTime = value;
  93741. },
  93742. enumerable: true,
  93743. configurable: true
  93744. });
  93745. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  93746. /**
  93747. * Gets the perf counter used for render time capture
  93748. */
  93749. get: function () {
  93750. return this._renderTime;
  93751. },
  93752. enumerable: true,
  93753. configurable: true
  93754. });
  93755. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  93756. /**
  93757. * Gets the render time capture status
  93758. */
  93759. get: function () {
  93760. return this._captureRenderTime;
  93761. },
  93762. /**
  93763. * Enable or disable the render time capture
  93764. */
  93765. set: function (value) {
  93766. var _this = this;
  93767. if (value === this._captureRenderTime) {
  93768. return;
  93769. }
  93770. this._captureRenderTime = value;
  93771. if (value) {
  93772. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  93773. _this._renderTime.beginMonitoring();
  93774. BABYLON.Tools.StartPerformanceCounter("Main render");
  93775. });
  93776. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  93777. _this._renderTime.endMonitoring(false);
  93778. BABYLON.Tools.EndPerformanceCounter("Main render");
  93779. });
  93780. }
  93781. else {
  93782. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  93783. this._onBeforeDrawPhaseObserver = null;
  93784. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  93785. this._onAfterDrawPhaseObserver = null;
  93786. }
  93787. },
  93788. enumerable: true,
  93789. configurable: true
  93790. });
  93791. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  93792. /**
  93793. * Gets the perf counter used for draw calls
  93794. */
  93795. get: function () {
  93796. return this.scene.getEngine()._drawCalls;
  93797. },
  93798. enumerable: true,
  93799. configurable: true
  93800. });
  93801. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  93802. /**
  93803. * Gets the perf counter used for texture collisions
  93804. */
  93805. get: function () {
  93806. return this.scene.getEngine()._textureCollisions;
  93807. },
  93808. enumerable: true,
  93809. configurable: true
  93810. });
  93811. SceneInstrumentation.prototype.dispose = function () {
  93812. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93813. this._onAfterRenderObserver = null;
  93814. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  93815. this._onBeforeActiveMeshesEvaluationObserver = null;
  93816. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  93817. this._onAfterActiveMeshesEvaluationObserver = null;
  93818. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  93819. this._onBeforeRenderTargetsRenderObserver = null;
  93820. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  93821. this._onAfterRenderTargetsRenderObserver = null;
  93822. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  93823. this._onBeforeAnimationsObserver = null;
  93824. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  93825. this._onBeforeParticlesRenderingObserver = null;
  93826. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  93827. this._onAfterParticlesRenderingObserver = null;
  93828. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  93829. this._onBeforeSpritesRenderingObserver = null;
  93830. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  93831. this._onAfterSpritesRenderingObserver = null;
  93832. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  93833. this._onBeforeDrawPhaseObserver = null;
  93834. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  93835. this._onAfterDrawPhaseObserver = null;
  93836. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  93837. this._onBeforePhysicsObserver = null;
  93838. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  93839. this._onAfterPhysicsObserver = null;
  93840. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  93841. this._onAfterAnimationsObserver = null;
  93842. this.scene = null;
  93843. };
  93844. return SceneInstrumentation;
  93845. }());
  93846. BABYLON.SceneInstrumentation = SceneInstrumentation;
  93847. })(BABYLON || (BABYLON = {}));
  93848. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  93849. "use strict";
  93850. var BABYLON;
  93851. (function (BABYLON) {
  93852. var _TimeToken = /** @class */ (function () {
  93853. function _TimeToken() {
  93854. this._timeElapsedQueryEnded = false;
  93855. }
  93856. return _TimeToken;
  93857. }());
  93858. BABYLON._TimeToken = _TimeToken;
  93859. })(BABYLON || (BABYLON = {}));
  93860. //# sourceMappingURL=babylon.timeToken.js.map
  93861. "use strict";
  93862. var BABYLON;
  93863. (function (BABYLON) {
  93864. /**
  93865. * Background material defines definition.
  93866. * @ignore Mainly internal Use
  93867. */
  93868. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  93869. __extends(BackgroundMaterialDefines, _super);
  93870. /**
  93871. * Constructor of the defines.
  93872. */
  93873. function BackgroundMaterialDefines() {
  93874. var _this = _super.call(this) || this;
  93875. /**
  93876. * True if the diffuse texture is in use.
  93877. */
  93878. _this.DIFFUSE = false;
  93879. /**
  93880. * The direct UV channel to use.
  93881. */
  93882. _this.DIFFUSEDIRECTUV = 0;
  93883. /**
  93884. * True if the diffuse texture is in gamma space.
  93885. */
  93886. _this.GAMMADIFFUSE = false;
  93887. /**
  93888. * True if the diffuse texture has opacity in the alpha channel.
  93889. */
  93890. _this.DIFFUSEHASALPHA = false;
  93891. /**
  93892. * True if you want the material to fade to transparent at grazing angle.
  93893. */
  93894. _this.OPACITYFRESNEL = false;
  93895. /**
  93896. * True if an extra blur needs to be added in the reflection.
  93897. */
  93898. _this.REFLECTIONBLUR = false;
  93899. /**
  93900. * True if you want the material to fade to reflection at grazing angle.
  93901. */
  93902. _this.REFLECTIONFRESNEL = false;
  93903. /**
  93904. * True if you want the material to falloff as far as you move away from the scene center.
  93905. */
  93906. _this.REFLECTIONFALLOFF = false;
  93907. /**
  93908. * False if the current Webgl implementation does not support the texture lod extension.
  93909. */
  93910. _this.TEXTURELODSUPPORT = false;
  93911. /**
  93912. * True to ensure the data are premultiplied.
  93913. */
  93914. _this.PREMULTIPLYALPHA = false;
  93915. /**
  93916. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  93917. */
  93918. _this.USERGBCOLOR = false;
  93919. /**
  93920. * True to add noise in order to reduce the banding effect.
  93921. */
  93922. _this.NOISE = false;
  93923. /**
  93924. * is the reflection texture in BGR color scheme?
  93925. * Mainly used to solve a bug in ios10 video tag
  93926. */
  93927. _this.REFLECTIONBGR = false;
  93928. _this.IMAGEPROCESSING = false;
  93929. _this.VIGNETTE = false;
  93930. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  93931. _this.VIGNETTEBLENDMODEOPAQUE = false;
  93932. _this.TONEMAPPING = false;
  93933. _this.CONTRAST = false;
  93934. _this.COLORCURVES = false;
  93935. _this.COLORGRADING = false;
  93936. _this.COLORGRADING3D = false;
  93937. _this.SAMPLER3DGREENDEPTH = false;
  93938. _this.SAMPLER3DBGRMAP = false;
  93939. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  93940. _this.EXPOSURE = false;
  93941. // Reflection.
  93942. _this.REFLECTION = false;
  93943. _this.REFLECTIONMAP_3D = false;
  93944. _this.REFLECTIONMAP_SPHERICAL = false;
  93945. _this.REFLECTIONMAP_PLANAR = false;
  93946. _this.REFLECTIONMAP_CUBIC = false;
  93947. _this.REFLECTIONMAP_PROJECTION = false;
  93948. _this.REFLECTIONMAP_SKYBOX = false;
  93949. _this.REFLECTIONMAP_EXPLICIT = false;
  93950. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  93951. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  93952. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  93953. _this.INVERTCUBICMAP = false;
  93954. _this.REFLECTIONMAP_OPPOSITEZ = false;
  93955. _this.LODINREFLECTIONALPHA = false;
  93956. _this.GAMMAREFLECTION = false;
  93957. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  93958. // Default BJS.
  93959. _this.MAINUV1 = false;
  93960. _this.MAINUV2 = false;
  93961. _this.UV1 = false;
  93962. _this.UV2 = false;
  93963. _this.CLIPPLANE = false;
  93964. _this.POINTSIZE = false;
  93965. _this.FOG = false;
  93966. _this.NORMAL = false;
  93967. _this.NUM_BONE_INFLUENCERS = 0;
  93968. _this.BonesPerMesh = 0;
  93969. _this.INSTANCES = false;
  93970. _this.SHADOWFLOAT = false;
  93971. _this.rebuild();
  93972. return _this;
  93973. }
  93974. return BackgroundMaterialDefines;
  93975. }(BABYLON.MaterialDefines));
  93976. /**
  93977. * Background material used to create an efficient environement around your scene.
  93978. */
  93979. var BackgroundMaterial = /** @class */ (function (_super) {
  93980. __extends(BackgroundMaterial, _super);
  93981. /**
  93982. * Instantiates a Background Material in the given scene
  93983. * @param name The friendly name of the material
  93984. * @param scene The scene to add the material to
  93985. */
  93986. function BackgroundMaterial(name, scene) {
  93987. var _this = _super.call(this, name, scene) || this;
  93988. /**
  93989. * Key light Color (multiply against the R channel of the environement texture)
  93990. */
  93991. _this.primaryColor = BABYLON.Color3.White();
  93992. /**
  93993. * Key light Level (allowing HDR output of the background)
  93994. */
  93995. _this.primaryLevel = 1;
  93996. /**
  93997. * Secondary light Color (multiply against the G channel of the environement texture)
  93998. */
  93999. _this.secondaryColor = BABYLON.Color3.Gray();
  94000. /**
  94001. * Secondary light Level (allowing HDR output of the background)
  94002. */
  94003. _this.secondaryLevel = 1;
  94004. /**
  94005. * Tertiary light Color (multiply against the B channel of the environement texture)
  94006. */
  94007. _this.tertiaryColor = BABYLON.Color3.Black();
  94008. /**
  94009. * Tertiary light Level (allowing HDR output of the background)
  94010. */
  94011. _this.tertiaryLevel = 1;
  94012. /**
  94013. * Reflection Texture used in the material.
  94014. * Should be author in a specific way for the best result (refer to the documentation).
  94015. */
  94016. _this.reflectionTexture = null;
  94017. /**
  94018. * Reflection Texture level of blur.
  94019. *
  94020. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  94021. * texture twice.
  94022. */
  94023. _this.reflectionBlur = 0;
  94024. /**
  94025. * Diffuse Texture used in the material.
  94026. * Should be author in a specific way for the best result (refer to the documentation).
  94027. */
  94028. _this.diffuseTexture = null;
  94029. _this._shadowLights = null;
  94030. /**
  94031. * Specify the list of lights casting shadow on the material.
  94032. * All scene shadow lights will be included if null.
  94033. */
  94034. _this.shadowLights = null;
  94035. /**
  94036. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  94037. * soft lighting on the background.
  94038. */
  94039. _this.shadowBlurScale = 1;
  94040. /**
  94041. * Helps adjusting the shadow to a softer level if required.
  94042. * 0 means black shadows and 1 means no shadows.
  94043. */
  94044. _this.shadowLevel = 0;
  94045. /**
  94046. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  94047. * It is usually zero but might be interesting to modify according to your setup.
  94048. */
  94049. _this.sceneCenter = BABYLON.Vector3.Zero();
  94050. /**
  94051. * This helps specifying that the material is falling off to the sky box at grazing angle.
  94052. * This helps ensuring a nice transition when the camera goes under the ground.
  94053. */
  94054. _this.opacityFresnel = true;
  94055. /**
  94056. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  94057. * This helps adding a mirror texture on the ground.
  94058. */
  94059. _this.reflectionFresnel = false;
  94060. /**
  94061. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  94062. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  94063. */
  94064. _this.reflectionFalloffDistance = 0.0;
  94065. /**
  94066. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  94067. */
  94068. _this.reflectionAmount = 1.0;
  94069. /**
  94070. * This specifies the weight of the reflection at grazing angle.
  94071. */
  94072. _this.reflectionReflectance0 = 0.05;
  94073. /**
  94074. * This specifies the weight of the reflection at a perpendicular point of view.
  94075. */
  94076. _this.reflectionReflectance90 = 0.5;
  94077. /**
  94078. * Helps to directly use the maps channels instead of their level.
  94079. */
  94080. _this.useRGBColor = true;
  94081. /**
  94082. * This helps reducing the banding effect that could occur on the background.
  94083. */
  94084. _this.enableNoise = false;
  94085. _this._fovMultiplier = 1.0;
  94086. /**
  94087. * Enable the FOV adjustment feature controlled by fovMultiplier.
  94088. */
  94089. _this.useEquirectangularFOV = false;
  94090. _this._maxSimultaneousLights = 4;
  94091. /**
  94092. * Number of Simultaneous lights allowed on the material.
  94093. */
  94094. _this.maxSimultaneousLights = 4;
  94095. /**
  94096. * Keep track of the image processing observer to allow dispose and replace.
  94097. */
  94098. _this._imageProcessingObserver = null;
  94099. /**
  94100. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  94101. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  94102. */
  94103. _this.switchToBGR = false;
  94104. // Temp values kept as cache in the material.
  94105. _this._renderTargets = new BABYLON.SmartArray(16);
  94106. _this._reflectionControls = BABYLON.Vector4.Zero();
  94107. // Setup the default processing configuration to the scene.
  94108. _this._attachImageProcessingConfiguration(null);
  94109. _this.getRenderTargetTextures = function () {
  94110. _this._renderTargets.reset();
  94111. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  94112. _this._renderTargets.push(_this._diffuseTexture);
  94113. }
  94114. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  94115. _this._renderTargets.push(_this._reflectionTexture);
  94116. }
  94117. return _this._renderTargets;
  94118. };
  94119. return _this;
  94120. }
  94121. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  94122. /**
  94123. * Sets the reflection reflectance fresnel values according to the default standard
  94124. * empirically know to work well :-)
  94125. */
  94126. set: function (value) {
  94127. var reflectionWeight = value;
  94128. if (reflectionWeight < 0.5) {
  94129. reflectionWeight = reflectionWeight * 2.0;
  94130. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  94131. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  94132. }
  94133. else {
  94134. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  94135. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  94136. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  94137. }
  94138. },
  94139. enumerable: true,
  94140. configurable: true
  94141. });
  94142. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  94143. /**
  94144. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  94145. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  94146. * Recommended to be keep at 1.0 except for special cases.
  94147. */
  94148. get: function () {
  94149. return this._fovMultiplier;
  94150. },
  94151. set: function (value) {
  94152. if (isNaN(value)) {
  94153. value = 1.0;
  94154. }
  94155. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  94156. },
  94157. enumerable: true,
  94158. configurable: true
  94159. });
  94160. /**
  94161. * Attaches a new image processing configuration to the PBR Material.
  94162. * @param configuration (if null the scene configuration will be use)
  94163. */
  94164. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  94165. var _this = this;
  94166. if (configuration === this._imageProcessingConfiguration) {
  94167. return;
  94168. }
  94169. // Detaches observer.
  94170. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  94171. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  94172. }
  94173. // Pick the scene configuration if needed.
  94174. if (!configuration) {
  94175. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  94176. }
  94177. else {
  94178. this._imageProcessingConfiguration = configuration;
  94179. }
  94180. // Attaches observer.
  94181. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  94182. _this._markAllSubMeshesAsImageProcessingDirty();
  94183. });
  94184. };
  94185. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  94186. /**
  94187. * Gets the image processing configuration used either in this material.
  94188. */
  94189. get: function () {
  94190. return this._imageProcessingConfiguration;
  94191. },
  94192. /**
  94193. * Sets the Default image processing configuration used either in the this material.
  94194. *
  94195. * If sets to null, the scene one is in use.
  94196. */
  94197. set: function (value) {
  94198. this._attachImageProcessingConfiguration(value);
  94199. // Ensure the effect will be rebuilt.
  94200. this._markAllSubMeshesAsTexturesDirty();
  94201. },
  94202. enumerable: true,
  94203. configurable: true
  94204. });
  94205. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  94206. /**
  94207. * Gets wether the color curves effect is enabled.
  94208. */
  94209. get: function () {
  94210. return this.imageProcessingConfiguration.colorCurvesEnabled;
  94211. },
  94212. /**
  94213. * Sets wether the color curves effect is enabled.
  94214. */
  94215. set: function (value) {
  94216. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  94217. },
  94218. enumerable: true,
  94219. configurable: true
  94220. });
  94221. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  94222. /**
  94223. * Gets wether the color grading effect is enabled.
  94224. */
  94225. get: function () {
  94226. return this.imageProcessingConfiguration.colorGradingEnabled;
  94227. },
  94228. /**
  94229. * Gets wether the color grading effect is enabled.
  94230. */
  94231. set: function (value) {
  94232. this.imageProcessingConfiguration.colorGradingEnabled = value;
  94233. },
  94234. enumerable: true,
  94235. configurable: true
  94236. });
  94237. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  94238. /**
  94239. * Gets wether tonemapping is enabled or not.
  94240. */
  94241. get: function () {
  94242. return this._imageProcessingConfiguration.toneMappingEnabled;
  94243. },
  94244. /**
  94245. * Sets wether tonemapping is enabled or not
  94246. */
  94247. set: function (value) {
  94248. this._imageProcessingConfiguration.toneMappingEnabled = value;
  94249. },
  94250. enumerable: true,
  94251. configurable: true
  94252. });
  94253. ;
  94254. ;
  94255. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  94256. /**
  94257. * The camera exposure used on this material.
  94258. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  94259. * This corresponds to a photographic exposure.
  94260. */
  94261. get: function () {
  94262. return this._imageProcessingConfiguration.exposure;
  94263. },
  94264. /**
  94265. * The camera exposure used on this material.
  94266. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  94267. * This corresponds to a photographic exposure.
  94268. */
  94269. set: function (value) {
  94270. this._imageProcessingConfiguration.exposure = value;
  94271. },
  94272. enumerable: true,
  94273. configurable: true
  94274. });
  94275. ;
  94276. ;
  94277. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  94278. /**
  94279. * Gets The camera contrast used on this material.
  94280. */
  94281. get: function () {
  94282. return this._imageProcessingConfiguration.contrast;
  94283. },
  94284. /**
  94285. * Sets The camera contrast used on this material.
  94286. */
  94287. set: function (value) {
  94288. this._imageProcessingConfiguration.contrast = value;
  94289. },
  94290. enumerable: true,
  94291. configurable: true
  94292. });
  94293. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  94294. /**
  94295. * Gets the Color Grading 2D Lookup Texture.
  94296. */
  94297. get: function () {
  94298. return this._imageProcessingConfiguration.colorGradingTexture;
  94299. },
  94300. /**
  94301. * Sets the Color Grading 2D Lookup Texture.
  94302. */
  94303. set: function (value) {
  94304. this.imageProcessingConfiguration.colorGradingTexture = value;
  94305. },
  94306. enumerable: true,
  94307. configurable: true
  94308. });
  94309. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  94310. /**
  94311. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  94312. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  94313. * 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;
  94314. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  94315. */
  94316. get: function () {
  94317. return this.imageProcessingConfiguration.colorCurves;
  94318. },
  94319. /**
  94320. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  94321. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  94322. * 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;
  94323. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  94324. */
  94325. set: function (value) {
  94326. this.imageProcessingConfiguration.colorCurves = value;
  94327. },
  94328. enumerable: true,
  94329. configurable: true
  94330. });
  94331. /**
  94332. * The entire material has been created in order to prevent overdraw.
  94333. * @returns false
  94334. */
  94335. BackgroundMaterial.prototype.needAlphaTesting = function () {
  94336. return true;
  94337. };
  94338. /**
  94339. * The entire material has been created in order to prevent overdraw.
  94340. * @returns true if blending is enable
  94341. */
  94342. BackgroundMaterial.prototype.needAlphaBlending = function () {
  94343. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  94344. };
  94345. /**
  94346. * Checks wether the material is ready to be rendered for a given mesh.
  94347. * @param mesh The mesh to render
  94348. * @param subMesh The submesh to check against
  94349. * @param useInstances Specify wether or not the material is used with instances
  94350. * @returns true if all the dependencies are ready (Textures, Effects...)
  94351. */
  94352. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  94353. var _this = this;
  94354. if (useInstances === void 0) { useInstances = false; }
  94355. if (subMesh.effect && this.isFrozen) {
  94356. if (this._wasPreviouslyReady) {
  94357. return true;
  94358. }
  94359. }
  94360. if (!subMesh._materialDefines) {
  94361. subMesh._materialDefines = new BackgroundMaterialDefines();
  94362. }
  94363. var scene = this.getScene();
  94364. var defines = subMesh._materialDefines;
  94365. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  94366. if (defines._renderId === scene.getRenderId()) {
  94367. return true;
  94368. }
  94369. }
  94370. var engine = scene.getEngine();
  94371. // Lights
  94372. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  94373. defines._needNormals = true;
  94374. // Textures
  94375. if (defines._areTexturesDirty) {
  94376. defines._needUVs = false;
  94377. if (scene.texturesEnabled) {
  94378. if (scene.getEngine().getCaps().textureLOD) {
  94379. defines.TEXTURELODSUPPORT = true;
  94380. }
  94381. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94382. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  94383. return false;
  94384. }
  94385. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  94386. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  94387. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  94388. defines.OPACITYFRESNEL = this._opacityFresnel;
  94389. }
  94390. else {
  94391. defines.DIFFUSE = false;
  94392. defines.DIFFUSEHASALPHA = false;
  94393. defines.GAMMADIFFUSE = false;
  94394. defines.OPACITYFRESNEL = false;
  94395. }
  94396. var reflectionTexture = this._reflectionTexture;
  94397. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94398. if (!reflectionTexture.isReadyOrNotBlocking()) {
  94399. return false;
  94400. }
  94401. defines.REFLECTION = true;
  94402. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  94403. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  94404. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  94405. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  94406. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  94407. defines.REFLECTIONBGR = this.switchToBGR;
  94408. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  94409. defines.INVERTCUBICMAP = true;
  94410. }
  94411. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  94412. switch (reflectionTexture.coordinatesMode) {
  94413. case BABYLON.Texture.CUBIC_MODE:
  94414. case BABYLON.Texture.INVCUBIC_MODE:
  94415. defines.REFLECTIONMAP_CUBIC = true;
  94416. break;
  94417. case BABYLON.Texture.EXPLICIT_MODE:
  94418. defines.REFLECTIONMAP_EXPLICIT = true;
  94419. break;
  94420. case BABYLON.Texture.PLANAR_MODE:
  94421. defines.REFLECTIONMAP_PLANAR = true;
  94422. break;
  94423. case BABYLON.Texture.PROJECTION_MODE:
  94424. defines.REFLECTIONMAP_PROJECTION = true;
  94425. break;
  94426. case BABYLON.Texture.SKYBOX_MODE:
  94427. defines.REFLECTIONMAP_SKYBOX = true;
  94428. break;
  94429. case BABYLON.Texture.SPHERICAL_MODE:
  94430. defines.REFLECTIONMAP_SPHERICAL = true;
  94431. break;
  94432. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  94433. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  94434. break;
  94435. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  94436. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  94437. break;
  94438. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  94439. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  94440. break;
  94441. }
  94442. if (this.reflectionFresnel) {
  94443. defines.REFLECTIONFRESNEL = true;
  94444. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  94445. this._reflectionControls.x = this.reflectionAmount;
  94446. this._reflectionControls.y = this.reflectionReflectance0;
  94447. this._reflectionControls.z = this.reflectionReflectance90;
  94448. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  94449. }
  94450. else {
  94451. defines.REFLECTIONFRESNEL = false;
  94452. defines.REFLECTIONFALLOFF = false;
  94453. }
  94454. }
  94455. else {
  94456. defines.REFLECTION = false;
  94457. defines.REFLECTIONFALLOFF = false;
  94458. defines.REFLECTIONBLUR = false;
  94459. defines.REFLECTIONMAP_3D = false;
  94460. defines.REFLECTIONMAP_SPHERICAL = false;
  94461. defines.REFLECTIONMAP_PLANAR = false;
  94462. defines.REFLECTIONMAP_CUBIC = false;
  94463. defines.REFLECTIONMAP_PROJECTION = false;
  94464. defines.REFLECTIONMAP_SKYBOX = false;
  94465. defines.REFLECTIONMAP_EXPLICIT = false;
  94466. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  94467. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  94468. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  94469. defines.INVERTCUBICMAP = false;
  94470. defines.REFLECTIONMAP_OPPOSITEZ = false;
  94471. defines.LODINREFLECTIONALPHA = false;
  94472. defines.GAMMAREFLECTION = false;
  94473. }
  94474. }
  94475. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  94476. defines.USERGBCOLOR = this._useRGBColor;
  94477. defines.NOISE = this._enableNoise;
  94478. }
  94479. if (defines._areImageProcessingDirty) {
  94480. if (!this._imageProcessingConfiguration.isReady()) {
  94481. return false;
  94482. }
  94483. this._imageProcessingConfiguration.prepareDefines(defines);
  94484. }
  94485. // Misc.
  94486. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  94487. // Values that need to be evaluated on every frame
  94488. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  94489. // Attribs
  94490. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  94491. if (mesh) {
  94492. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  94493. mesh.createNormals(true);
  94494. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  94495. }
  94496. }
  94497. }
  94498. // Get correct effect
  94499. if (defines.isDirty) {
  94500. defines.markAsProcessed();
  94501. scene.resetCachedMaterial();
  94502. // Fallbacks
  94503. var fallbacks = new BABYLON.EffectFallbacks();
  94504. if (defines.FOG) {
  94505. fallbacks.addFallback(0, "FOG");
  94506. }
  94507. if (defines.POINTSIZE) {
  94508. fallbacks.addFallback(1, "POINTSIZE");
  94509. }
  94510. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  94511. if (defines.NUM_BONE_INFLUENCERS > 0) {
  94512. fallbacks.addCPUSkinningFallback(0, mesh);
  94513. }
  94514. //Attributes
  94515. var attribs = [BABYLON.VertexBuffer.PositionKind];
  94516. if (defines.NORMAL) {
  94517. attribs.push(BABYLON.VertexBuffer.NormalKind);
  94518. }
  94519. if (defines.UV1) {
  94520. attribs.push(BABYLON.VertexBuffer.UVKind);
  94521. }
  94522. if (defines.UV2) {
  94523. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94524. }
  94525. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  94526. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  94527. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  94528. "vFogInfos", "vFogColor", "pointSize",
  94529. "vClipPlane", "mBones",
  94530. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  94531. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  94532. "shadowLevel", "alpha",
  94533. "vBackgroundCenter", "vReflectionControl",
  94534. "vDiffuseInfos", "diffuseMatrix",
  94535. ];
  94536. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  94537. var uniformBuffers = ["Material", "Scene"];
  94538. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  94539. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  94540. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  94541. uniformsNames: uniforms,
  94542. uniformBuffersNames: uniformBuffers,
  94543. samplers: samplers,
  94544. defines: defines,
  94545. maxSimultaneousLights: this._maxSimultaneousLights
  94546. });
  94547. var onCompiled = function (effect) {
  94548. if (_this.onCompiled) {
  94549. _this.onCompiled(effect);
  94550. }
  94551. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  94552. };
  94553. var join = defines.toString();
  94554. subMesh.setEffect(scene.getEngine().createEffect("background", {
  94555. attributes: attribs,
  94556. uniformsNames: uniforms,
  94557. uniformBuffersNames: uniformBuffers,
  94558. samplers: samplers,
  94559. defines: join,
  94560. fallbacks: fallbacks,
  94561. onCompiled: onCompiled,
  94562. onError: this.onError,
  94563. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  94564. }, engine), defines);
  94565. this.buildUniformLayout();
  94566. }
  94567. if (!subMesh.effect || !subMesh.effect.isReady()) {
  94568. return false;
  94569. }
  94570. defines._renderId = scene.getRenderId();
  94571. this._wasPreviouslyReady = true;
  94572. return true;
  94573. };
  94574. /**
  94575. * Build the uniform buffer used in the material.
  94576. */
  94577. BackgroundMaterial.prototype.buildUniformLayout = function () {
  94578. // Order is important !
  94579. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  94580. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  94581. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  94582. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  94583. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  94584. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  94585. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  94586. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  94587. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  94588. this._uniformBuffer.addUniform("pointSize", 1);
  94589. this._uniformBuffer.addUniform("shadowLevel", 1);
  94590. this._uniformBuffer.addUniform("alpha", 1);
  94591. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  94592. this._uniformBuffer.addUniform("vReflectionControl", 4);
  94593. this._uniformBuffer.create();
  94594. };
  94595. /**
  94596. * Unbind the material.
  94597. */
  94598. BackgroundMaterial.prototype.unbind = function () {
  94599. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  94600. this._uniformBuffer.setTexture("diffuseSampler", null);
  94601. }
  94602. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  94603. this._uniformBuffer.setTexture("reflectionSampler", null);
  94604. }
  94605. _super.prototype.unbind.call(this);
  94606. };
  94607. /**
  94608. * Bind only the world matrix to the material.
  94609. * @param world The world matrix to bind.
  94610. */
  94611. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  94612. this._activeEffect.setMatrix("world", world);
  94613. };
  94614. /**
  94615. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  94616. * @param world The world matrix to bind.
  94617. * @param subMesh The submesh to bind for.
  94618. */
  94619. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  94620. var scene = this.getScene();
  94621. var defines = subMesh._materialDefines;
  94622. if (!defines) {
  94623. return;
  94624. }
  94625. var effect = subMesh.effect;
  94626. if (!effect) {
  94627. return;
  94628. }
  94629. this._activeEffect = effect;
  94630. // Matrices
  94631. this.bindOnlyWorldMatrix(world);
  94632. // Bones
  94633. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  94634. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  94635. if (mustRebind) {
  94636. this._uniformBuffer.bindToEffect(effect, "Material");
  94637. this.bindViewProjection(effect);
  94638. var reflectionTexture = this._reflectionTexture;
  94639. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  94640. // Texture uniforms
  94641. if (scene.texturesEnabled) {
  94642. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94643. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  94644. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  94645. }
  94646. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94647. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  94648. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  94649. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  94650. }
  94651. }
  94652. if (this.shadowLevel > 0) {
  94653. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  94654. }
  94655. this._uniformBuffer.updateFloat("alpha", this.alpha);
  94656. // Point size
  94657. if (this.pointsCloud) {
  94658. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  94659. }
  94660. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  94661. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  94662. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  94663. }
  94664. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  94665. // Textures
  94666. if (scene.texturesEnabled) {
  94667. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94668. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  94669. }
  94670. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94671. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  94672. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  94673. }
  94674. else if (!defines.REFLECTIONBLUR) {
  94675. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  94676. }
  94677. else {
  94678. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  94679. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  94680. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  94681. }
  94682. if (defines.REFLECTIONFRESNEL) {
  94683. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  94684. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  94685. }
  94686. }
  94687. }
  94688. // Clip plane
  94689. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  94690. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  94691. }
  94692. if (mustRebind || !this.isFrozen) {
  94693. if (scene.lightsEnabled) {
  94694. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  94695. }
  94696. // View
  94697. this.bindView(effect);
  94698. // Fog
  94699. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  94700. // image processing
  94701. this._imageProcessingConfiguration.bind(this._activeEffect);
  94702. }
  94703. this._uniformBuffer.update();
  94704. this._afterBind(mesh);
  94705. };
  94706. /**
  94707. * Dispose the material.
  94708. * @param forceDisposeEffect Force disposal of the associated effect.
  94709. * @param forceDisposeTextures Force disposal of the associated textures.
  94710. */
  94711. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  94712. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  94713. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  94714. if (forceDisposeTextures) {
  94715. if (this.diffuseTexture) {
  94716. this.diffuseTexture.dispose();
  94717. }
  94718. if (this.reflectionTexture) {
  94719. this.reflectionTexture.dispose();
  94720. }
  94721. }
  94722. this._renderTargets.dispose();
  94723. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  94724. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  94725. }
  94726. _super.prototype.dispose.call(this, forceDisposeEffect);
  94727. };
  94728. /**
  94729. * Clones the material.
  94730. * @param name The cloned name.
  94731. * @returns The cloned material.
  94732. */
  94733. BackgroundMaterial.prototype.clone = function (name) {
  94734. var _this = this;
  94735. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  94736. };
  94737. /**
  94738. * Serializes the current material to its JSON representation.
  94739. * @returns The JSON representation.
  94740. */
  94741. BackgroundMaterial.prototype.serialize = function () {
  94742. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94743. serializationObject.customType = "BABYLON.BackgroundMaterial";
  94744. return serializationObject;
  94745. };
  94746. /**
  94747. * Gets the class name of the material
  94748. * @returns "BackgroundMaterial"
  94749. */
  94750. BackgroundMaterial.prototype.getClassName = function () {
  94751. return "BackgroundMaterial";
  94752. };
  94753. /**
  94754. * Parse a JSON input to create back a background material.
  94755. * @param source The JSON data to parse
  94756. * @param scene The scene to create the parsed material in
  94757. * @param rootUrl The root url of the assets the material depends upon
  94758. * @returns the instantiated BackgroundMaterial.
  94759. */
  94760. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  94761. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  94762. };
  94763. /**
  94764. * Standard reflectance value at parallel view angle.
  94765. */
  94766. BackgroundMaterial.StandardReflectance0 = 0.05;
  94767. /**
  94768. * Standard reflectance value at grazing angle.
  94769. */
  94770. BackgroundMaterial.StandardReflectance90 = 0.5;
  94771. __decorate([
  94772. BABYLON.serializeAsColor3()
  94773. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  94774. __decorate([
  94775. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94776. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  94777. __decorate([
  94778. BABYLON.serialize()
  94779. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  94780. __decorate([
  94781. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94782. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  94783. __decorate([
  94784. BABYLON.serializeAsColor3()
  94785. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  94786. __decorate([
  94787. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94788. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  94789. __decorate([
  94790. BABYLON.serialize()
  94791. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  94792. __decorate([
  94793. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94794. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  94795. __decorate([
  94796. BABYLON.serializeAsColor3()
  94797. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  94798. __decorate([
  94799. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94800. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  94801. __decorate([
  94802. BABYLON.serialize()
  94803. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  94804. __decorate([
  94805. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94806. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  94807. __decorate([
  94808. BABYLON.serializeAsTexture()
  94809. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  94810. __decorate([
  94811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94812. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  94813. __decorate([
  94814. BABYLON.serialize()
  94815. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  94816. __decorate([
  94817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94818. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  94819. __decorate([
  94820. BABYLON.serializeAsTexture()
  94821. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  94822. __decorate([
  94823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94824. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  94825. __decorate([
  94826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94827. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  94828. __decorate([
  94829. BABYLON.serialize()
  94830. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  94831. __decorate([
  94832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94833. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  94834. __decorate([
  94835. BABYLON.serialize()
  94836. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  94837. __decorate([
  94838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94839. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  94840. __decorate([
  94841. BABYLON.serializeAsVector3()
  94842. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  94843. __decorate([
  94844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94845. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  94846. __decorate([
  94847. BABYLON.serialize()
  94848. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  94849. __decorate([
  94850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94851. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  94852. __decorate([
  94853. BABYLON.serialize()
  94854. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  94855. __decorate([
  94856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94857. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  94858. __decorate([
  94859. BABYLON.serialize()
  94860. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  94861. __decorate([
  94862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94863. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  94864. __decorate([
  94865. BABYLON.serialize()
  94866. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  94867. __decorate([
  94868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94869. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  94870. __decorate([
  94871. BABYLON.serialize()
  94872. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  94873. __decorate([
  94874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94875. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  94876. __decorate([
  94877. BABYLON.serialize()
  94878. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  94879. __decorate([
  94880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94881. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  94882. __decorate([
  94883. BABYLON.serialize()
  94884. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  94885. __decorate([
  94886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94887. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  94888. __decorate([
  94889. BABYLON.serialize()
  94890. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  94891. __decorate([
  94892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94893. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  94894. __decorate([
  94895. BABYLON.serialize()
  94896. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  94897. __decorate([
  94898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94899. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  94900. __decorate([
  94901. BABYLON.serializeAsImageProcessingConfiguration()
  94902. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  94903. return BackgroundMaterial;
  94904. }(BABYLON.PushMaterial));
  94905. BABYLON.BackgroundMaterial = BackgroundMaterial;
  94906. })(BABYLON || (BABYLON = {}));
  94907. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  94908. "use strict";
  94909. var __assign = (this && this.__assign) || Object.assign || function(t) {
  94910. for (var s, i = 1, n = arguments.length; i < n; i++) {
  94911. s = arguments[i];
  94912. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  94913. t[p] = s[p];
  94914. }
  94915. return t;
  94916. };
  94917. var BABYLON;
  94918. (function (BABYLON) {
  94919. /**
  94920. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  94921. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  94922. * It also helps with the default setup of your imageProcessing configuration.
  94923. */
  94924. var EnvironmentHelper = /** @class */ (function () {
  94925. /**
  94926. * constructor
  94927. * @param options
  94928. * @param scene The scene to add the material to
  94929. */
  94930. function EnvironmentHelper(options, scene) {
  94931. var _this = this;
  94932. this._errorHandler = function (message, exception) {
  94933. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  94934. };
  94935. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  94936. this._scene = scene;
  94937. this.onErrorObservable = new BABYLON.Observable();
  94938. this._setupBackground();
  94939. this._setupImageProcessing();
  94940. }
  94941. /**
  94942. * Creates the default options for the helper.
  94943. */
  94944. EnvironmentHelper._getDefaultOptions = function () {
  94945. return {
  94946. createGround: true,
  94947. groundSize: 15,
  94948. groundTexture: this._groundTextureCDNUrl,
  94949. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  94950. groundOpacity: 0.9,
  94951. enableGroundShadow: true,
  94952. groundShadowLevel: 0.5,
  94953. enableGroundMirror: false,
  94954. groundMirrorSizeRatio: 0.3,
  94955. groundMirrorBlurKernel: 64,
  94956. groundMirrorAmount: 1,
  94957. groundMirrorFresnelWeight: 1,
  94958. groundMirrorFallOffDistance: 0,
  94959. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  94960. groundYBias: 0.00001,
  94961. createSkybox: true,
  94962. skyboxSize: 20,
  94963. skyboxTexture: this._skyboxTextureCDNUrl,
  94964. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  94965. backgroundYRotation: 0,
  94966. sizeAuto: true,
  94967. rootPosition: BABYLON.Vector3.Zero(),
  94968. setupImageProcessing: true,
  94969. environmentTexture: this._environmentTextureCDNUrl,
  94970. cameraExposure: 0.8,
  94971. cameraContrast: 1.2,
  94972. toneMappingEnabled: true,
  94973. };
  94974. };
  94975. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  94976. /**
  94977. * Gets the root mesh created by the helper.
  94978. */
  94979. get: function () {
  94980. return this._rootMesh;
  94981. },
  94982. enumerable: true,
  94983. configurable: true
  94984. });
  94985. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  94986. /**
  94987. * Gets the skybox created by the helper.
  94988. */
  94989. get: function () {
  94990. return this._skybox;
  94991. },
  94992. enumerable: true,
  94993. configurable: true
  94994. });
  94995. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  94996. /**
  94997. * Gets the skybox texture created by the helper.
  94998. */
  94999. get: function () {
  95000. return this._skyboxTexture;
  95001. },
  95002. enumerable: true,
  95003. configurable: true
  95004. });
  95005. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  95006. /**
  95007. * Gets the skybox material created by the helper.
  95008. */
  95009. get: function () {
  95010. return this._skyboxMaterial;
  95011. },
  95012. enumerable: true,
  95013. configurable: true
  95014. });
  95015. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  95016. /**
  95017. * Gets the ground mesh created by the helper.
  95018. */
  95019. get: function () {
  95020. return this._ground;
  95021. },
  95022. enumerable: true,
  95023. configurable: true
  95024. });
  95025. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  95026. /**
  95027. * Gets the ground texture created by the helper.
  95028. */
  95029. get: function () {
  95030. return this._groundTexture;
  95031. },
  95032. enumerable: true,
  95033. configurable: true
  95034. });
  95035. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  95036. /**
  95037. * Gets the ground mirror created by the helper.
  95038. */
  95039. get: function () {
  95040. return this._groundMirror;
  95041. },
  95042. enumerable: true,
  95043. configurable: true
  95044. });
  95045. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  95046. /**
  95047. * Gets the ground mirror render list to helps pushing the meshes
  95048. * you wish in the ground reflection.
  95049. */
  95050. get: function () {
  95051. if (this._groundMirror) {
  95052. return this._groundMirror.renderList;
  95053. }
  95054. return null;
  95055. },
  95056. enumerable: true,
  95057. configurable: true
  95058. });
  95059. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  95060. /**
  95061. * Gets the ground material created by the helper.
  95062. */
  95063. get: function () {
  95064. return this._groundMaterial;
  95065. },
  95066. enumerable: true,
  95067. configurable: true
  95068. });
  95069. /**
  95070. * Updates the background according to the new options
  95071. * @param options
  95072. */
  95073. EnvironmentHelper.prototype.updateOptions = function (options) {
  95074. var newOptions = __assign({}, this._options, options);
  95075. if (this._ground && !newOptions.createGround) {
  95076. this._ground.dispose();
  95077. this._ground = null;
  95078. }
  95079. if (this._groundMaterial && !newOptions.createGround) {
  95080. this._groundMaterial.dispose();
  95081. this._groundMaterial = null;
  95082. }
  95083. if (this._groundTexture) {
  95084. if (this._options.groundTexture != newOptions.groundTexture) {
  95085. this._groundTexture.dispose();
  95086. this._groundTexture = null;
  95087. }
  95088. }
  95089. if (this._skybox && !newOptions.createSkybox) {
  95090. this._skybox.dispose();
  95091. this._skybox = null;
  95092. }
  95093. if (this._skyboxMaterial && !newOptions.createSkybox) {
  95094. this._skyboxMaterial.dispose();
  95095. this._skyboxMaterial = null;
  95096. }
  95097. if (this._skyboxTexture) {
  95098. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  95099. this._skyboxTexture.dispose();
  95100. this._skyboxTexture = null;
  95101. }
  95102. }
  95103. if (this._groundMirror && !newOptions.enableGroundMirror) {
  95104. this._groundMirror.dispose();
  95105. this._groundMirror = null;
  95106. }
  95107. if (this._scene.environmentTexture) {
  95108. if (this._options.environmentTexture != newOptions.environmentTexture) {
  95109. this._scene.environmentTexture.dispose();
  95110. }
  95111. }
  95112. this._options = newOptions;
  95113. this._setupBackground();
  95114. this._setupImageProcessing();
  95115. };
  95116. /**
  95117. * Sets the primary color of all the available elements.
  95118. * @param color
  95119. */
  95120. EnvironmentHelper.prototype.setMainColor = function (color) {
  95121. if (this.groundMaterial) {
  95122. this.groundMaterial.primaryColor = color;
  95123. }
  95124. if (this.skyboxMaterial) {
  95125. this.skyboxMaterial.primaryColor = color;
  95126. }
  95127. if (this.groundMirror) {
  95128. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  95129. }
  95130. };
  95131. /**
  95132. * Setup the image processing according to the specified options.
  95133. */
  95134. EnvironmentHelper.prototype._setupImageProcessing = function () {
  95135. if (this._options.setupImageProcessing) {
  95136. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  95137. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  95138. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  95139. this._setupEnvironmentTexture();
  95140. }
  95141. };
  95142. /**
  95143. * Setup the environment texture according to the specified options.
  95144. */
  95145. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  95146. if (this._scene.environmentTexture) {
  95147. return;
  95148. }
  95149. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  95150. this._scene.environmentTexture = this._options.environmentTexture;
  95151. return;
  95152. }
  95153. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  95154. this._scene.environmentTexture = environmentTexture;
  95155. };
  95156. /**
  95157. * Setup the background according to the specified options.
  95158. */
  95159. EnvironmentHelper.prototype._setupBackground = function () {
  95160. if (!this._rootMesh) {
  95161. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  95162. }
  95163. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  95164. var sceneSize = this._getSceneSize();
  95165. if (this._options.createGround) {
  95166. this._setupGround(sceneSize);
  95167. this._setupGroundMaterial();
  95168. this._setupGroundDiffuseTexture();
  95169. if (this._options.enableGroundMirror) {
  95170. this._setupGroundMirrorTexture(sceneSize);
  95171. }
  95172. this._setupMirrorInGroundMaterial();
  95173. }
  95174. if (this._options.createSkybox) {
  95175. this._setupSkybox(sceneSize);
  95176. this._setupSkyboxMaterial();
  95177. this._setupSkyboxReflectionTexture();
  95178. }
  95179. this._rootMesh.position.x = sceneSize.rootPosition.x;
  95180. this._rootMesh.position.z = sceneSize.rootPosition.z;
  95181. this._rootMesh.position.y = sceneSize.rootPosition.y;
  95182. };
  95183. /**
  95184. * Get the scene sizes according to the setup.
  95185. */
  95186. EnvironmentHelper.prototype._getSceneSize = function () {
  95187. var _this = this;
  95188. var groundSize = this._options.groundSize;
  95189. var skyboxSize = this._options.skyboxSize;
  95190. var rootPosition = this._options.rootPosition;
  95191. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  95192. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  95193. }
  95194. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  95195. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  95196. });
  95197. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  95198. if (this._options.sizeAuto) {
  95199. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  95200. this._scene.activeCamera.upperRadiusLimit) {
  95201. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  95202. skyboxSize = groundSize;
  95203. }
  95204. var sceneDiagonalLenght = sceneDiagonal.length();
  95205. if (sceneDiagonalLenght > groundSize) {
  95206. groundSize = sceneDiagonalLenght * 2;
  95207. skyboxSize = groundSize;
  95208. }
  95209. // 10 % bigger.
  95210. groundSize *= 1.1;
  95211. skyboxSize *= 1.5;
  95212. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  95213. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  95214. }
  95215. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  95216. };
  95217. /**
  95218. * Setup the ground according to the specified options.
  95219. */
  95220. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  95221. var _this = this;
  95222. if (!this._ground) {
  95223. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  95224. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  95225. this._ground.parent = this._rootMesh;
  95226. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  95227. }
  95228. this._ground.receiveShadows = this._options.enableGroundShadow;
  95229. };
  95230. /**
  95231. * Setup the ground material according to the specified options.
  95232. */
  95233. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  95234. if (!this._groundMaterial) {
  95235. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  95236. }
  95237. this._groundMaterial.alpha = this._options.groundOpacity;
  95238. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  95239. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  95240. this._groundMaterial.primaryLevel = 1;
  95241. this._groundMaterial.primaryColor = this._options.groundColor;
  95242. this._groundMaterial.secondaryLevel = 0;
  95243. this._groundMaterial.tertiaryLevel = 0;
  95244. this._groundMaterial.useRGBColor = false;
  95245. this._groundMaterial.enableNoise = true;
  95246. if (this._ground) {
  95247. this._ground.material = this._groundMaterial;
  95248. }
  95249. };
  95250. /**
  95251. * Setup the ground diffuse texture according to the specified options.
  95252. */
  95253. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  95254. if (!this._groundMaterial) {
  95255. return;
  95256. }
  95257. if (this._groundTexture) {
  95258. return;
  95259. }
  95260. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  95261. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  95262. return;
  95263. }
  95264. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  95265. diffuseTexture.gammaSpace = false;
  95266. diffuseTexture.hasAlpha = true;
  95267. this._groundMaterial.diffuseTexture = diffuseTexture;
  95268. };
  95269. /**
  95270. * Setup the ground mirror texture according to the specified options.
  95271. */
  95272. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  95273. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95274. if (!this._groundMirror) {
  95275. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  95276. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  95277. this._groundMirror.anisotropicFilteringLevel = 1;
  95278. this._groundMirror.wrapU = wrapping;
  95279. this._groundMirror.wrapV = wrapping;
  95280. this._groundMirror.gammaSpace = false;
  95281. if (this._groundMirror.renderList) {
  95282. for (var i = 0; i < this._scene.meshes.length; i++) {
  95283. var mesh = this._scene.meshes[i];
  95284. if (mesh !== this._ground &&
  95285. mesh !== this._skybox &&
  95286. mesh !== this._rootMesh) {
  95287. this._groundMirror.renderList.push(mesh);
  95288. }
  95289. }
  95290. }
  95291. }
  95292. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  95293. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  95294. };
  95295. /**
  95296. * Setup the ground to receive the mirror texture.
  95297. */
  95298. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  95299. if (this._groundMaterial) {
  95300. this._groundMaterial.reflectionTexture = this._groundMirror;
  95301. this._groundMaterial.reflectionFresnel = true;
  95302. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  95303. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  95304. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  95305. }
  95306. };
  95307. /**
  95308. * Setup the skybox according to the specified options.
  95309. */
  95310. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  95311. var _this = this;
  95312. if (!this._skybox) {
  95313. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  95314. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  95315. }
  95316. this._skybox.parent = this._rootMesh;
  95317. };
  95318. /**
  95319. * Setup the skybox material according to the specified options.
  95320. */
  95321. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  95322. if (!this._skybox) {
  95323. return;
  95324. }
  95325. if (!this._skyboxMaterial) {
  95326. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  95327. }
  95328. this._skyboxMaterial.useRGBColor = false;
  95329. this._skyboxMaterial.primaryLevel = 1;
  95330. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  95331. this._skyboxMaterial.secondaryLevel = 0;
  95332. this._skyboxMaterial.tertiaryLevel = 0;
  95333. this._skyboxMaterial.enableNoise = true;
  95334. this._skybox.material = this._skyboxMaterial;
  95335. };
  95336. /**
  95337. * Setup the skybox reflection texture according to the specified options.
  95338. */
  95339. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  95340. if (!this._skyboxMaterial) {
  95341. return;
  95342. }
  95343. if (this._skyboxTexture) {
  95344. return;
  95345. }
  95346. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  95347. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  95348. return;
  95349. }
  95350. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  95351. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  95352. this._skyboxTexture.gammaSpace = false;
  95353. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  95354. };
  95355. /**
  95356. * Dispose all the elements created by the Helper.
  95357. */
  95358. EnvironmentHelper.prototype.dispose = function () {
  95359. if (this._groundMaterial) {
  95360. this._groundMaterial.dispose(true, true);
  95361. }
  95362. if (this._skyboxMaterial) {
  95363. this._skyboxMaterial.dispose(true, true);
  95364. }
  95365. this._rootMesh.dispose(false);
  95366. };
  95367. /**
  95368. * Default ground texture URL.
  95369. */
  95370. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  95371. /**
  95372. * Default skybox texture URL.
  95373. */
  95374. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  95375. /**
  95376. * Default environment texture URL.
  95377. */
  95378. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  95379. return EnvironmentHelper;
  95380. }());
  95381. BABYLON.EnvironmentHelper = EnvironmentHelper;
  95382. })(BABYLON || (BABYLON = {}));
  95383. //# sourceMappingURL=babylon.environmentHelper.js.map
  95384. "use strict";
  95385. var BABYLON;
  95386. (function (BABYLON) {
  95387. /**
  95388. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  95389. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  95390. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  95391. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  95392. */
  95393. var VideoDome = /** @class */ (function (_super) {
  95394. __extends(VideoDome, _super);
  95395. /**
  95396. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  95397. * @param name Element's name, child elements will append suffixes for their own names.
  95398. * @param urlsOrVideo
  95399. * @param options An object containing optional or exposed sub element properties:
  95400. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  95401. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  95402. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  95403. * @param options **loop=true** Automatically loop video on end.
  95404. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  95405. */
  95406. function VideoDome(name, urlsOrVideo, options, scene) {
  95407. var _this = _super.call(this, name, scene) || this;
  95408. // set defaults and manage values
  95409. name = name || "videoDome";
  95410. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  95411. options.clickToPlay = Boolean(options.clickToPlay);
  95412. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  95413. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  95414. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  95415. // create
  95416. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  95417. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  95418. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  95419. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  95420. flat: false,
  95421. radius: options.size,
  95422. subdivisions: options.resolution,
  95423. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  95424. }, scene);
  95425. // configure material
  95426. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  95427. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  95428. material.reflectionTexture = _this._videoTexture;
  95429. material.useEquirectangularFOV = true;
  95430. material.fovMultiplier = 1.0;
  95431. // configure mesh
  95432. _this._mesh.material = material;
  95433. _this._mesh.parent = _this;
  95434. // optional configuration
  95435. if (options.clickToPlay) {
  95436. scene.onPointerUp = function () {
  95437. _this._videoTexture.video.play();
  95438. };
  95439. }
  95440. return _this;
  95441. }
  95442. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  95443. /**
  95444. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  95445. * Also see the options.resolution property.
  95446. */
  95447. get: function () {
  95448. return this._material.fovMultiplier;
  95449. },
  95450. set: function (value) {
  95451. this._material.fovMultiplier = value;
  95452. },
  95453. enumerable: true,
  95454. configurable: true
  95455. });
  95456. /**
  95457. * Releases resources associated with this node.
  95458. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  95459. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  95460. */
  95461. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  95462. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  95463. this._videoTexture.dispose();
  95464. this._mesh.dispose();
  95465. this._material.dispose();
  95466. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  95467. };
  95468. return VideoDome;
  95469. }(BABYLON.Node));
  95470. BABYLON.VideoDome = VideoDome;
  95471. })(BABYLON || (BABYLON = {}));
  95472. //# sourceMappingURL=babylon.videoDome.js.map
  95473. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\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<0.4)\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(GEOMETRYAA)\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#ifdef GEOMETRYAA\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#include<bumpFragment>\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 GEOMETRYAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(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).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=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*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,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*=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;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","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 vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*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); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-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;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\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);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\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}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=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*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\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,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"};
  95474. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\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=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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};"};
  95475. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  95476. globalObject["BABYLON"] = BABYLON;
  95477. //backwards compatibility
  95478. if(typeof earcut !== 'undefined') {
  95479. globalObject["Earcut"] = {
  95480. earcut: earcut
  95481. };
  95482. }
  95483. return BABYLON;
  95484. });